gpt4 book ai didi

Javascript HTML5 Canvas 绘制透明圆圈

转载 作者:太空狗 更新时间:2023-10-29 15:48:50 25 4
gpt4 key购买 nike

我需要一个函数来在 Canvas 上绘制几个圆,从 center=x,y 处的 mousedown 开始,然后将鼠标拖动到 deltaX,deltaY,从而为每个圆创建半径 r。圆圈不能有填充物(需要它们透明),因此用户可以清楚地看到圆圈 chop 的位置。我当前的代码在拖动鼠标时绘制圆圈,这是预期的,但它也会留下那些额外的圆圈。我只需要在 mouseup 上留下圆圈。任何帮助表示赞赏。谢谢 :)。

<html>

<head>

</head>

<body style="margin:0">
<canvas id="canvas" width="500" height="500" style="border:1px solid"></canvas>

<script>

var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
var radius=50;
var nStartX = 0;
var nStartY = 0;
var bIsDrawing = false;
var putPoint = function(e){
nStartX = e.clientX;nStartY = e.clientY;
bIsDrawing = true;
radius = 0;
}
var drawPoint = function(e){
if(!bIsDrawing)
return;

var nDeltaX = nStartX - e.clientX;
var nDeltaY = nStartY - e.clientY;
radius = Math.sqrt(nDeltaX * nDeltaX + nDeltaY * nDeltaY)
context.beginPath();
context.arc(nStartX, nStartY, radius, 0, Math.PI*2);
context.strokeStyle="#000000";
//context.fillStyle="#FFFFFF";
context.fillStyle = 'rgba(0, 0, 0, 0)';
context.stroke();
context.fill();
}
var stopPoint = function(e){
//context.clip();
//context.clearRect(0, 0, canvas.width, canvas.height);
bIsDrawing = false;
}
canvas.addEventListener('mousedown',putPoint);
canvas.addEventListener('mousemove',drawPoint);
canvas.addEventListener('mouseup',stopPoint);

</script>
</body>

</html>

最佳答案

您需要跟踪您绘制的圆圈(和其他对象)——一种方法是在 mouseup 上将它们插入数组。然后每次绘制之前都应该清除 Canvas 并重新绘制已保存的圆圈。

var circles = [];
...

清除 Canvas

...
radius = Math.sqrt(nDeltaX * nDeltaX + nDeltaY * nDeltaY)
context.clearRect(0, 0, canvas.width, canvas.height);
...

绘制保存的圆圈

...
context.fill();
// drawing saved circles
circles.forEach(function(circle){
context.beginPath();
context.arc(circle.nStartX, circle.nStartY, circle.radius, 0, Math.PI*2);
context.strokeStyle="#000000";
context.fillStyle="#FFFFFF";
context.fillStyle = 'rgba(0, 0, 0, 0)';
context.stroke();
context.fill();
})
...

保存完成的圈子

...
bIsDrawing = false;
// saving completed circles
var nDeltaX = nStartX - e.clientX;
var nDeltaY = nStartY - e.clientY;
radius = Math.sqrt(nDeltaX * nDeltaX + nDeltaY * nDeltaY);
circles.push({ nStartX: nStartX, nStartY: nStartY, radius: radius });
...

fiddle - https://jsfiddle.net/9x77sg2h/

关于Javascript HTML5 Canvas 绘制透明圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36622930/

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