【问题标题】:How to add rectangle/arrow to my canvas line?如何在我的画布线上添加矩形/箭头?
【发布时间】:2016-06-02 03:23:46
【问题描述】:

我有这段代码可以在 html 画布上显示风向:

var x, y, r, ctx, radians;

  ctx = window.compass.getContext("2d");

  radians = 0.0174533 * (10 - 90);
  x = ctx.canvas.width / 2;
  y = ctx.canvas.height / 2;
  r = x * 0.8;

  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height );
  ctx.beginPath();
  ctx.strokeStyle = "red"
  ctx.fillStyle = "rgba(255,0,0,0.5)";
  ctx.lineCap = 'square';
  ctx.shadowOffsetX = 4;
  ctx.shadowOffsetY = 4;
  ctx.shadowBlur = 2;
  ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
  ctx.lineWidth = 10;

  ctx.moveTo(x, y);
  ctx.lineTo(x + r * Math.cos(radians), y + r * Math.sin(radians));
  ctx.stroke();

我想在线条的起点添加箭头,即

x = ctx.canvas.width / 2; y = ctx.canvas.height / 2;

我该怎么做?

【问题讨论】:

  • 参见this answer 作为参考。只需按照说明围绕头部旋转并用箭头替换圆圈即可。
  • 在 html 画布中太难了
  • 似乎是这样.. 我能想到的最好的办法是在我的起点画一个圆圈,它是静态的,不会随着我的线条变化而变化。不是很好的解决方案。

标签: javascript html canvas


【解决方案1】:

创建可重复使用的风箭相当简单:

  1. 在内存画布上创建阴影箭头:

    var memCanvas=document.createElement('canvas')
    
  2. 将内存中的画布绘制到可见画布上:

    ctx.drawImage(memCanvas,x,y);
    

这是示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var cx=150;
var cy=150;
var angle=0;

var arrow=makeArrow(100,10,20,20,'red',4);

requestAnimationFrame(animate);

function animate(time){
    ctx.clearRect(0,0,cw,ch);
    drawArrow(cx,cy,angle);
    angle+=Math.PI/180;
    requestAnimationFrame(animate);
}

function drawArrow(cx,cy,radianAngle){
    ctx.translate(cx,cy);
    ctx.rotate(radianAngle);
    ctx.drawImage(arrow,-arrow.width/2,-arrow.height/2);
    ctx.rotate(-radianAngle);
    ctx.translate(-cx,-cy);
}

function makeArrow(length,lineHeight,arrowLength,arrowHeight,fillcolor,shadowoffset){
    var lineTop=(arrowHeight-lineHeight)/2;
    var arrowLeft=length-arrowLength;
    var c=document.createElement('canvas');
    var ctx=c.getContext('2d');
    c.width=length+shadowoffset;
    c.height=arrowHeight+shadowoffset;

    ctx.shadowOffsetX = shadowoffset;
    ctx.shadowOffsetY = shadowoffset;
    ctx.shadowBlur = 2;
    ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
      
    ctx.beginPath();
    ctx.moveTo(0,lineTop);
    ctx.lineTo(arrowLeft,lineTop);
    ctx.lineTo(arrowLeft,0);
    ctx.lineTo(length,arrowHeight/2);
    ctx.lineTo(arrowLeft,arrowHeight);
    ctx.lineTo(arrowLeft,lineTop+lineHeight);
    ctx.lineTo(0,lineTop+lineHeight);
    ctx.closePath();
    ctx.fillStyle=fillcolor;
    ctx.fill();
    return(c);
}
body{ background-color:white; padding:10px; }
canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-13
    • 2016-01-22
    • 2014-02-08
    • 2012-05-09
    • 1970-01-01
    • 2017-01-26
    • 2019-05-25
    • 2023-03-28
    相关资源
    最近更新 更多