SVG中的内联文本编辑

时间:2012-02-16 09:50:09

标签: javascript svg

我在网站中渲染内联SVG,并且必须使用户能够以所见即所得的方式在该SVG中添加和修改文本。基本上我需要一些像svg-edit一样的东西。但是我不需要完全WYSIWYG编辑器,只需要内联文本编辑部分。我查看了svg-edit的源代码,似乎很难只提取它的那一部分。

所以我正在寻找的是一种简单的方法(可能是第三方库)来实现内联SVG文本编辑。我已经考虑过在聚焦时用HTML文本输入替换SVG文本,但是文本必须在编辑模式下呈现,就像在生成的SVG中呈现一样。

5 个答案:

答案 0 :(得分:14)

编辑:对于现在找到这个答案的任何人来说,该项目已经停止,并且从未达到成熟阶段:(

我一直在寻找类似的东西,但没有找到任何东西,所以我和我的硕士论文合作伙伴决定编写我们自己的解决方案。目前它在Chrome中运行得相当好,在Firefox中也相当不错。

演示:http://engelfrost.github.io/svg-input-elements/

代码:https://github.com/engelfrost/svg-input-elements

答案 1 :(得分:12)

无论你在SVG中点击什么,我都会创建一个可编辑的文本。最后一步是获取HTML文本并将其放在SVG元素中。

http://jsfiddle.net/brx3xm59/

代码如下:

var mousedownonelement = false;

window.getlocalmousecoord = function (svg, evt) {
    var pt = svg.createSVGPoint();
    pt.x = evt.clientX;
    pt.y = evt.clientY;
    var localpoint = pt.matrixTransform(svg.getScreenCTM().inverse());
    localpoint.x = Math.round(localpoint.x);
    localpoint.y = Math.round(localpoint.y);
    return localpoint;
};

window.createtext = function (localpoint, svg) {
    var myforeign = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject')
    var textdiv = document.createElement("div");
    var textnode = document.createTextNode("Click to edit");
    textdiv.appendChild(textnode);
    textdiv.setAttribute("contentEditable", "true");
    textdiv.setAttribute("width", "auto");
    myforeign.setAttribute("width", "100%");
    myforeign.setAttribute("height", "100%");
    myforeign.classList.add("foreign"); //to make div fit text
    textdiv.classList.add("insideforeign"); //to make div fit text
    textdiv.addEventListener("mousedown", elementMousedown, false);
    myforeign.setAttributeNS(null, "transform", "translate(" + localpoint.x + " " + localpoint.y + ")");
    svg.appendChild(myforeign);
    myforeign.appendChild(textdiv);

};

function elementMousedown(evt) {
    mousedownonelement = true;
}


$(('#thesvg')).click(function (evt) {
    var svg = document.getElementById('thesvg');
    var localpoint = getlocalmousecoord(svg, evt);
    if (!mousedownonelement) {
        createtext(localpoint, svg);
    } else {
        mousedownonelement = false;
    }
});

答案 2 :(得分:0)

以下是一个示例,您可以从textnode获取和更改文本。我建议编写一个JavaScript函数,将一个可编辑的div或类似的东西放在textnode的位置,并在保存时用innerHTML的{​​{1}}替换textnode。

成功后请在此发布最终代码。

div

答案 3 :(得分:0)

编辑:更新示例以使用Edge。客户端边界框的属性在那里有所不同-这可能是下面报告的旧版iPad和Safari的问题。我已经在Edge,Chrome,FF,Safari(Mac)和Chrome,FF,Safari(iPad)上对此进行了测试。在Edge上,光标已断开,但编辑仍然有效。

我意识到这是一个古老的问题,但是如果您不想实现自己的输入元素行为,那么contentEditable技巧仍然是我们所拥有的。如果使用单个svg文本节点(而不是HTML外部对象)作为要编辑的文本的覆盖,则可以得到真正的WSYWIG,因为您可以使用与原始文本相同的字体等。您还可以选择可以编辑的元素。是的,游标在Safari中很奇怪。可以在这里找到证明这一点的小提琴:

https://jsfiddle.net/AaronDavidNewman/ta0jhw1q/

HTML / SVG:

<div id="yyy">

  <div id="xxx">

    <svg width="500" height="500" viewBox="0 0 500 500">
      <text x="0" y="25" id="target1" font-size="1.8em">Change me</text>
      <text x="0" y="50" id="targetx" font-size="1.8em">You can't edit me</text>
      <text x="0" y="75" id="target2" font-size="1.8em">Edit me</text>
      <text x="0" y="100" id="targety" font-size="1.8em">You can't edit me</text>
      <text x="0" y="125" id="target3" font-size="1.8em">Improve me</text>
    </svg>
  </div>
  <div id="aaa" contentEditable="true" class="hide">
    <svg width="500" height="50" viewBox="0 0 500 50">
      <text x="0" y="50" id="input-area" font-size="1.8em"></text>
    </svg>
  </div>
</div>

Javascript:

 // Create in-place editable text elements in svg.  Click inside the element 
// to edit it, and away to stop editing and switch to another element
var editing = false;
var svgns = "http://www.w3.org/2000/svg";
$('body').css('overflow','hidden');

// Poll on changes to input element.  A better approach might be 
// to update after keyboard events
var editElement = function(aaa, xxx) {
  setTimeout(function() {
    xxx.textContent = aaa.textContent;
    if (editing) {     
      editElement(aaa, xxx);
    }
  }, 250);
}

// Make sure the input svg element is placed directly over the 
// target element
var fixOffset = function(aaa, xxx) {
  var svg = $('#xxx').find('svg')[0];
  $('.underEdit').remove();
  var rect = xxx.getBoundingClientRect();
  var offset = aaa.getBoundingClientRect();
  $('#aaa').css('left', rect.left + (rect.left - offset.left));
  $('#aaa').css('top', rect.top + (rect.top - offset.top));
  var bb = xxx.getBBox();
  var margin = 10;
}
// Based on a click in the element svg area, edit that element
var editId = function(id) {
  var aaa = document.getElementById('input-area');
  var xxx = document.getElementById(id);
  var rect = xxx.getBoundingClientRect();
  $('#aaa').css('left', rect.left);
  $('#aaa').css('top', rect.top);
  setTimeout(function() {
    fixOffset(aaa, xxx);
  }, 1);
  aaa.textContent = xxx.textContent;
  editing = true;
  editElement(aaa, xxx);
}
// see if a click intersects an editable element
var getIntersection = function(objs, point) {
  var rv = null;
  $(objs).each(function(ix, obj) {
    var i1 = point.x - obj.box.x;
    var i2 = point.y - obj.box.y;
    // If inside the box, we have an element to edit
    if (i1 > 0 && i1 < obj.box.width && i2 > 0 && i2 < obj.box.height) {
      rv = obj;
      return false;
    } else if (i1 > -10 && i1 < obj.box.width + 10 && i2 > -10 && i2 < obj.box.height + 10) {
       // edit a nearby click, if a better match isn't found
      rv = obj;
    }
  });
  return rv;
}

// bind editable elements to mouse click
var bind = function(texts) {
  var objs = [];
  // find geometry of each editable element
  texts.forEach((id) => {
    var el = document.getElementById(id);
    var bbox = el.getBoundingClientRect();
    bbox = { x: bbox.left, y: bbox.top, width: bbox.width, height: bbox.height };
    objs.push({id: id, box: bbox });
  });
  // bind click event globally, then try to find the intersection.
  $(document).off('click').on('click', function(ev) {

    var point = {x: ev.clientX, y: ev.clientY };
    console.log('x:' + point.x + 'y:' + point.y);
    var obj = getIntersection(objs, point);
    if (obj && !editing) {
      $('#aaa').removeClass('hide');
      editing = true;
      console.log('start edit on ' + obj.id);
      editId(obj.id);
    } else if (!obj) {
      {
        $('#aaa').addClass('hide');
        editing = false;
        $('.underEdit').remove();
        console.log('stop editing');
      }
    }
  });
}

bind(['target1', 'target2', 'target3']);

CSS:

#yyy {
  position: relative;
  width: 500px;
  height: 500px;
}

#xxx {
  position: absolute;
  left: 100px;
  top: 100px;
  z-index: 1;
}

#aaa {
  position: absolute;
  left: 100px;
  top: 100px;
  z-index: 2;
  overflow:hidden;
}

.hide {
  display: none;
}

答案 4 :(得分:0)

这是一个演示,它可以编辑已经存在的文本(而不是创建新的文本条目): https://jsfiddle.net/qkrLy9gu enter image description here

<!DOCTYPE html>
<html>
<body>

<svg height="100" width="200">
    <circle cx="50" cy="50" r="40" fill="red"/>
    <text x="50" y="50" onclick="edittext(this)">a circle [click to edit]</text>
</svg> 

<script>
function edittext(svgtext){
    var input = document.createElement("input");
    input.value = svgtext.textContent
    input.onkeyup = function(e){    
        if (["Enter", "Escape"].includes(e.key)) {this.blur(); return};
        svgtext.textContent = this.value
    }
    input.onblur = function(e){       
        myforeign.remove()
    }

    var myforeign = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject')
    myforeign.setAttribute("width", "100%");
    myforeign.setAttribute("height", "100%");
    myforeign.append(input);
    
    svg = svgtext.parentNode
    svg.append(myforeign);

    input.focus()
}
</script>
 
</body>
</html>