如何拖动通过按钮单击插入的svg?

时间:2018-10-10 02:00:23

标签: svg canvas drag

我想做的是通过单击工作区的按钮来插入svg圆。除此之外,我想自由拖动所有这些圆圈。 你能帮我代码吗?

document.getElementById('draw').addEventListener('click', function(){

document.getElementById('here').innerHTML = 
'<svg height="100" width="100">' + 
  '<circle cx="50" cy="50" r="40" stroke="black" stroke-width="1" fill="rgba(130,130,130,0.6)">' + 
'</svg>';

});
<button id="draw">Draw Circle</button>
<div id="here"></div>

1 个答案:

答案 0 :(得分:2)

让我惊讶的是,创建这样的SVG可行,而且可行! (也在IE上)。但是,在尝试使用事件时会产生问题。我更喜欢使用createElementNS创建SVG元素和circle元素,并使用appendChild将它们附加到DOM

const SVG_NS = 'http://www.w3.org/2000/svg';
const SVG_XLINK = "http://www.w3.org/1999/xlink";


/*let innerSVG = '<svg height="100" width="100">' + 
  '<circle cx="50" cy="50" r="40" stroke="black" stroke-width="1" fill="rgba(130,130,130,0.6)">' + 
'</svg>';*/

let svgdata =  {width:100,height:100}
let circledata = {cx:50,cy:50,r:40}
// creating a new SVG element using the data
let svg = newSVG(svgdata);
// creating a new circle element using the data and appending it to the svg
let circle = drawCircle(circledata, svg);
// the offset between the click point on the SVG and the left upper corner of the SVG
let offset={}
// a flag to control the dragging
let dragging = false;
// the mouse position
let m;
document.getElementById('draw').addEventListener('click', function(){

here.appendChild(svg)});


// events
here.addEventListener("mousedown",(evt)=>{
  dragging = true;
  offset = oMousePos(svg, evt);
})

here.addEventListener("mousemove",(evt)=>{
  if(dragging){
   m = oMousePos(here, evt);
   svg.style.top = (m.y - offset.y)+"px";
   svg.style.left = (m.x - offset.x)+"px";
  }
})

here.addEventListener("mouseup",(evt)=>{
  dragging = false;
})




function drawCircle(o, parent) {
  var circle = document.createElementNS(SVG_NS, 'circle');
  for (var name in o) {
    if (o.hasOwnProperty(name)) {
      circle.setAttributeNS(null, name, o[name]);
    }
  }
  parent.appendChild(circle);
  return circle;
}


function newSVG(o) {
  let svg = document.createElementNS(SVG_NS, 'svg');
  for (var name in o) {
    if (o.hasOwnProperty(name)) {
      svg.setAttributeNS(null, name, o[name]);
    }
  }
  return svg;
}



function oMousePos(elmt, evt) {
      let ClientRect = elmt.getBoundingClientRect();
                return { 
                x: Math.round(evt.clientX - ClientRect.left),
                y: Math.round(evt.clientY - ClientRect.top)
      }
}
svg{border:1px solid;position:absolute;}

circle{
  stroke:black;stroke-width:1;fill:rgba(130,130,130,0.6);
}

#here{width:100%; height:100vh; background-color:#efefef;margin:0; padding:0; position:relative}
<button id="draw">Draw Circle</button>
<div id="here"></div>