我只是在问题时,画多个圆圈在画布上。当我画一个圆圈刚刚成功,但下一个圆圈第一个圆圈不见了。实际上只有一个圆圈是存在的。所以,请给我的东西在我的代码为多个圆圈,
这是我的密码
html
<canvas id="canvas" width="800" height="500"></canvas>
JS
//Canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//Variables
var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;
var last_mousex = last_mousey = 0;
var mousex = mousey = 0;
var mousedown = false;
//Mousedown
$(canvas).on('mousedown', function(e) {
last_mousex = parseInt(e.clientX-canvasx);
last_mousey = parseInt(e.clientY-canvasy);
mousedown = true;
});
//Mouseup
$(canvas).on('mouseup', function(e) {
mousedown = false;
});
//Mousemove
$(canvas).on('mousemove', function(e) {
mousex = parseInt(e.clientX-canvasx);
mousey = parseInt(e.clientY-canvasy);
if(mousedown) {
ctx.clearRect(0,0,canvas.width,canvas.height);
//Save
ctx.save();
ctx.beginPath();
//Dynamic scaling
var scalex = 1*((mousex-last_mousex)/2);
var scaley = 1*((mousey-last_mousey)/2);
ctx.scale(scalex,scaley);
//Create ellipse
var centerx = (last_mousex/scalex)+1;
var centery = (last_mousey/scaley)+1;
ctx.arc(centerx, centery, 1, 0, 2*Math.PI);
//Restore and draw
ctx.restore();
ctx.strokeStyle = 'black';
ctx.lineWidth = 5;
ctx.stroke();
}
});`
1条答案
按热度按时间mutmk8jj1#
ctx.clearRect
函数会在每次点击和移动鼠标时清除画布,因此会清除之前的圆并在其上绘制新的圆。但是如果删除该函数,则每次移动鼠标时都会创建一个新的圆,这不是您想要的。我的解决方案是添加一个数组变量
circles
,用于在每次执行mouseup
时存储圆的坐标,然后在清除画布后循环circles
数组以绘制圆。此外,我还移除了逻辑,将圆绘制成函数。以下是具体操作: