繁体   English   中英

如何用鼠标在画布上绘制箭头

[英]How can I draw arrows on a canvas with mouse

最近我开始玩画布元素。 现在我可以用鼠标在画布上画线(任意多)。 你可以在代码中看到它: https : //jsfiddle.net/saipavan579/a6L3ka8p/

var ctx = tempcanvas.getContext('2d'),
mainctx = canvas.getContext('2d'),
w = canvas.width,
h = canvas.height,
x1,
y1,
isDown = false;

tempcanvas.onmousedown = function(e) {
var pos = getPosition(e, canvas);
x1      = pos.x;
y1      = pos.y;
isDown = true;
}
tempcanvas.onmouseup = function() {
isDown = false;
mainctx.drawImage(tempcanvas, 0, 0);
ctx.clearRect(0, 0, w, h);
}
tempcanvas.onmousemove = function(e) {

if (!isDown) return;

var pos = getPosition(e, canvas);
x2      = pos.x;
y2      = pos.y;

ctx.clearRect(0, 0, w, h);
drawEllipse(x1, y1, x2, y2);

}

function drawEllipse(x1, y1, x2, y2) {
var radiusX = (x2 - x1) * 0.5,
    radiusY = (y2 - y1) * 0.5,
    centerX = x1 + radiusX,
    centerY = y1 + radiusY,
    step = 0.01,
    a = step,
    pi2 = Math.PI * 2 - step;

ctx.beginPath();
ctx.moveTo(x1,y1);

for(; a < pi2; a += step) {
    ctx.lineTo(x2,y2);
}

ctx.closePath();
ctx.strokeStyle = '#000';
ctx.stroke();
}

function getPosition(e, gCanvasElement) {
var x;
var y;
               
x = e.pageX;
y = e.pageY;

x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
                    
return {x:x, y:y};
};      

现在我想以与绘制线条相同的方式绘制箭头线(用于指向图像上的某个特定点)。 怎么能这样? 先感谢您。

在此处输入图片说明

您可以像这样在线段 [p0,p1] 的末尾绘制一个箭头:

  • 使用 Math.atan2 计算从 p0 到 p1 的角度。

  • 箭头的每一边都从 p1 开始,因此使用三角法计算 2 个箭头端点。

  • 绘制 [p0,p1] 线段和 2 条箭头线段。

这是示例代码和演示:

 var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var p0={x:50,y:100}; var p1={x:250,y:50}; drawLineWithArrowhead(p0,p1,15); function drawLineWithArrowhead(p0,p1,headLength){ // constants (could be declared as globals outside this function) var PI=Math.PI; var degreesInRadians225=225*PI/180; var degreesInRadians135=135*PI/180; // calc the angle of the line var dx=p1.x-p0.x; var dy=p1.y-p0.y; var angle=Math.atan2(dy,dx); // calc arrowhead points var x225=p1.x+headLength*Math.cos(angle+degreesInRadians225); var y225=p1.y+headLength*Math.sin(angle+degreesInRadians225); var x135=p1.x+headLength*Math.cos(angle+degreesInRadians135); var y135=p1.y+headLength*Math.sin(angle+degreesInRadians135); // draw line plus arrowhead ctx.beginPath(); // draw the line from p0 to p1 ctx.moveTo(p0.x,p0.y); ctx.lineTo(p1.x,p1.y); // draw partial arrowhead at 225 degrees ctx.moveTo(p1.x,p1.y); ctx.lineTo(x225,y225); // draw partial arrowhead at 135 degrees ctx.moveTo(p1.x,p1.y); ctx.lineTo(x135,y135); // stroke the line and arrowhead ctx.stroke(); }
 body{ background-color: ivory; } canvas{border:1px solid red;}
 <canvas id="canvas" width=300 height=300></canvas>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM