Move Dynamically Created Svg With Mouse
Solution 1:
A few observations: your code is correct, however it's extremely verbose so I needed to reduce it. In the code you'll find a function to create an SVG element from an object. I'm using this function to create the svg elements and the circles.
Also I'm putting the SVG elements in an array. It's easier to wotk with similar elements when you have them in an array.
The main idea is:
The svg elements have
position:absolute
. The position of the svg can be set using thetop
andleft
properties in cssOn mouse down drag is true. If drag is true you can drag the svg element. The new position of the svg (it's
top
andleft
properties) are set in css in function of the mouse position and the distancedelta
between the mouse and the top left corner of the SVG element.On mouse up drag is false. The svg element can't be dragged any longer.
Please read the code and the comments and let me know if you don't understand.
constSVG_NS = "http://www.w3.org/2000/svg";
let svg1 = {
width: 100,
height: 100
};
let circle1 = {
cx: 80,
cy: 80,
r: 30,
fill: "red"
};
let drag = null;// a flag to know if you can drag or notlet _array = [];// the array of scg elementslet delta = {};// distance between the mouse and the top left coener of the SVG elementlet m = {};// mouse positionfunctioncreateSVGElement(o, elmtName, parent) {
var elmt = document.createElementNS(SVG_NS, elmtName);
for (var name in o) {
if (o.hasOwnProperty(name)) {
elmt.setAttributeNS(null, name, o[name]);
}
}
parent.appendChild(elmt);
return elmt;
}
let firstsvg = createSVGElement(svg1, "svg", svg54583);
let firstCircle = createSVGElement(circle1, "circle", firstsvg);
let secondsvg = createSVGElement(svg1, "svg", svg54583);
let secondCircle = createSVGElement(circle1, "circle", secondsvg);
_array.push(firstsvg);
_array.push(secondsvg);
_array.forEach((svg, i) => {
svg.addEventListener("mousedown", evt => {
// you can drag
drag = i + 1; // i + 1 because 0 is false. I need it to be truelet pos = svg.getBoundingClientRect();
// distance between the mouse and the top left coener of the SVG
delta.x = evt.clientX - pos.x;
delta.y = evt.clientY - pos.y;
});
});
svg54583.addEventListener("mousemove", evt => {
if (drag) {
m = oMousePos(svg54583, evt); //console.log("m",m);
_array[drag - 1].style.left = m.x - delta.x + "px";
_array[drag - 1].style.top = m.y - delta.y + "px";
}
});
svg54583.addEventListener("mouseup", evt => {
drag = null;
});
functionoMousePos(elmt, evt) {
varClientRect = elmt.getBoundingClientRect();
return {
//objetox: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
};
}
*{margin:0;padding:0;}
svg{border:1px solid; position:absolute;background:white;}
svg:nth-of-type(2){left:200px;}
#svg54583{width:100vw; height:100vh; background:lightGrey; border:1px solid;}
<divid="svg54583"></div>
Post a Comment for "Move Dynamically Created Svg With Mouse"