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

时间:2014-11-07 15:35:16

标签: javascript html5 canvas

最近我开始玩 canvas 元素。现在我可以在带有鼠标的画布上绘制线条(尽可能多)。您可以在代码中看到它:http://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};
};      

现在我想绘制箭头线(用于指向图像上的某个特定点),就像绘制线条一样。怎么办?提前谢谢。

1 个答案:

答案 0 :(得分:5)

enter image description here

您可以在线段[p0,p1]的末尾画一个箭头,如下所示:

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

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

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

以下是示例代码和演示:

&#13;
&#13;
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();
}
&#13;
body{ background-color: ivory; }
canvas{border:1px solid red;}
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;
&#13;
&#13;