如何在我的画布线上添加矩形/箭头?

时间:2016-06-01 12:22:28

标签: javascript html5 canvas

我有这段代码在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;

我该怎么做?

1 个答案:

答案 0 :(得分:0)

创建可重复使用的风箭非常简单:

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

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

    ctx.drawImage(memCanvas,x,y);
    
  3. enter image description here enter image description here

    以下是示例代码和演示:

    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>