如何在鼠标移动时在画布上绘制CIRCLE
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在鼠标移动时在画布上绘制CIRCLE相关的知识,希望对你有一定的参考价值。
我试图在鼠标移动时在画布上绘制一个圆圈,但没有成功。我的代码如下:
var damages_canvas = document.getElementById('damages-area');
var ctx_damages = damages_canvas.getContext('2d');
var circle_rect = damages_canvas.getBoundingClientRect();
var circle_drag = false;
var circle_canvas_update = true;
var circles = [];
var markerColor = "#f00";
damages_canvas.addEventListener('mousedown', drawCircleMouseDown, false);
damages_canvas.addEventListener('mouseup', drawCircleMouseUp, false);
damages_canvas.addEventListener('mousemove', drawCircleMouseMove, false);
requestAnimationFrame(updateCircleCanvas);
function updateCircleCanvas(){
if(circle_canvas_update){
drawCircleCanvas();
circle_canvas_update = false;
}
requestAnimationFrame(updateCircleCanvas);
}
function drawCircle(circle){
var startX = circle.startX,
endX = circle.endX,
startY = circle.startY,
endY = circle.endY;
ctx_damages.clearRect(0,0,damages_canvas.width,damages_canvas.height);
ctx_damages.beginPath();
ctx_damages.moveTo(startX, startY + (endY-startY)/2);
ctx_damages.bezierCurveTo(startX, startY, endX, startY, endX, startY + (endX-startY)/2);
ctx_damages.bezierCurveTo(endX, endY, startX, endY, startX, startY + (endY-startY)/2);
ctx_damages.closePath();
ctx_damages.stroke();
}
function drawCircleCanvas(){
ctx_damages.setTransform(1,0,0,1,0,0);
ctx_damages.clearRect(0, 0, damages_canvas.width, damages_canvas.height);
ctx_damages.fillStyle = "transparent"; // Color
ctx_damages.strokeStyle = markerColor; // Color
circles.forEach(drawCircle)
}
function drawCircleMouseDown(e){
circle = {
startX : e.offsetX - circle_rect.left,
startY : e.offsetY - circle_rect.top,
endX : 10,
endY : 10
};
circle_drag = true;
circles.push(circle);
circle_canvas_update = true;
}
function drawCircleMouseUp(){
circle_drag = false;
circle_canvas_update = true;
}
function drawCircleMouseMove(e){
if(circle_drag){
circle.endX = e.offsetX - circle_rect.left;
circle.endY = e.offsetY - circle_rect.top;
circle_canvas_update = true;
}
}
#damages-area {background:#f9f9f9}
<canvas id="damages-area" width=600 height=600></canvas>
我想绘制一个圆圈,而不是省略号或其他任何东西。但就我而言,我得到一些奇怪的东西。
不知道怎么办呢?
以上是关于如何在鼠标移动时在画布上绘制CIRCLE的主要内容,如果未能解决你的问题,请参考以下文章
如何在鼠标单击时在 FigureCanvasQTAgg 上画一个圆圈