Reputation: 27
I have written some code in javascript, which allows the user to manipulate a circle inside a svg.
I provided some code below. Here you can move a circle. On Chrome as well as Egde it works perfectly. On Firefox it does not work. When I move the circle, it teleports nearly every second pixel to the top left corner. I have the version 67.0.4.
The following code is using a svg by the id "svg" from inside a html file.
const svg = document.getElementById('svg');
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "100px");
circle.setAttribute("cy", "100px");
circle.setAttribute("r", "50px");
circle.setAttribute("fill", "blue");
svg.appendChild(circle);
let pressed = false;
svg.addEventListener("mousedown", (e) => {
pressed = true;
});
svg.addEventListener("mousemove", (e) => {
if (pressed) {
circle.setAttribute("cx", e.offsetX);
circle.setAttribute("cy", e.offsetY);
}
});
svg.addEventListener("mouseup", (e) => {
pressed = false;
});
Upvotes: 1
Views: 61
Reputation: 2167
USE clientX
and clientY
. I think offsetX
and offsetY
are deprecated in Firefox
const svg = document.getElementById('svg');
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "100px");
circle.setAttribute("cy", "100px");
circle.setAttribute("r", "50px");
circle.setAttribute("fill", "blue");
svg.appendChild(circle);
let pressed = false;
svg.addEventListener("mousedown", (e) => {
pressed = true;
});
svg.addEventListener("mousemove", (e) => {
if (pressed) {
circle.setAttribute("cx", e.clientX);
circle.setAttribute("cy", e.clientY);
}
});
svg.addEventListener("mouseup", (e) => {
pressed = false;
});
svg {
background: grey;
}
<svg id="svg" width="300" height="200"><svg>
Upvotes: 1