我用 javascript 编写了一些代码,允许用户在 svg 中操作圆圈。
我在下面提供了一些代码。在这里你可以移动一个圆圈。在 Chrome 和 Egde 上它都能完美运行。在 Firefox 上它不起作用。当我移动圆圈时,它几乎每隔一个像素就会传送到左上角。我的版本是 67.0.4。
以下代码使用 html 文件中 ID 为“svg”的 svg。
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;
});
最佳答案
使用 clientX
和 clientY
。我认为 offsetX
和 offsetY
在 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>
关于javascript - 如何使用 offsetX 和 offsetY 在 firefox 浏览器中的 svg 内移动一个圆圈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56954246/