gpt4 book ai didi

javascript - 如何通过鼠标移动在 SVG 上绘制矩形?

转载 作者:行者123 更新时间:2023-11-30 07:49:05 26 4
gpt4 key购买 nike

我在某人的 fiddle 上找到了代码在鼠标移动时描边(单击并移动描边)。我的要求是以相同的方式用鼠标移动在 SVG 上描边矩形。是否可能,如果可能,如何实现?

//Canvas
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
//Variables
let canvasx = canvas.offsetLeft;
let canvasy = canvas.offsetTop;
let last_mousex = 0;
let last_mousey = 0;
let mousex = 0;
let mousey = 0;
let mousedown = false;

//Mousedown
canvas.onmousedown = ({
clientX,
clientY
}) => {
last_mousex = parseInt(clientX - canvasx);
last_mousey = parseInt(clientY - canvasy);
mousedown = true;
};

//Mouseup
canvas.onmouseup = () => mousedown = false;


//Mousemove

canvas.onmousemove = ({
clientX,
clientY
}) => {
mousex = parseInt(clientX - canvasx);
mousey = parseInt(clientY - canvasy);
if (mousedown) {
ctx.clearRect(0, 0, canvas.width, canvas.height); //clear canvas
ctx.beginPath();
const width = mousex - last_mousex;
const height = mousey - last_mousey;
ctx.rect(last_mousex, last_mousey, width, height);
ctx.strokeStyle = 'black';
ctx.lineWidth = 10;
ctx.stroke();
}
};
canvas {
cursor: crosshair;
border: 1px solid #000000;
}
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Title</title>
</head>

<body>

<canvas id="canvas" width="800" height="500"></canvas>

</body>

</html>

Some Code// To prevent Stackoverflow error, please ignore

最佳答案

为了完全模仿 canvas 方法的行为,使您能够通过单击并向任何方向拖动(即从右下角到左上角或反之亦然)来绘制矩形,您需要根据当前鼠标坐标相对于初始 mousedown 点的位置,有条件地处理 x、y、宽度和高度值。此外,下面的代码片段包含一个函数,如果您在转换后的 SVG 元素(或转换后的子元素)上“绘图”,该函数会返回正确的坐标。

const svg = document.querySelector('#svg');
const svgPoint = (elem, x, y) => {
const p = svg.createSVGPoint();
p.x = x;
p.y = y;
return p.matrixTransform(elem.getScreenCTM().inverse());
};

svg.addEventListener('mousedown', (event) => {
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
const start = svgPoint(svg, event.clientX, event.clientY);
const drawRect = (e) => {
const p = svgPoint(svg, e.clientX, e.clientY);
const w = Math.abs(p.x - start.x);
const h = Math.abs(p.y - start.y);
if (p.x > start.x) {
p.x = start.x;
}

if (p.y > start.y) {
p.y = start.y;
}

rect.setAttributeNS(null, 'x', p.x);
rect.setAttributeNS(null, 'y', p.y);
rect.setAttributeNS(null, 'width', w);
rect.setAttributeNS(null, 'height', h);
svg.appendChild(rect);
};

const endDraw = (e) => {
svg.removeEventListener('mousemove', drawRect);
svg.removeEventListener('mouseup', endDraw);
};

svg.addEventListener('mousemove', drawRect);
svg.addEventListener('mouseup', endDraw);
});
svg {
cursor: crosshair;
border: 1px solid #000000;
}

rect {
fill: none;
stroke: #000000;
stroke-width: 10;
}
<svg id="svg" width="800" height="500"></svg>

关于javascript - 如何通过鼠标移动在 SVG 上绘制矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57502704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com