canvas绘制箭头

发布时间 2023-10-11 11:12:16作者: boye169
<!DOCTYPE html>
<html>
<head>
    <title>箭头</title>
    <meta charset="utf-8">
</head>

<body style="">
    <canvas id="'myCanvas" width="1500" height="2000" ></canvas>
</body>

<script type="text/javascript">
    var canvas = document.getElementById("'myCanvas");
    var ctx = canvas.getContext("2d");
    function drawArrow(ctx, fromX, fromY, toX, toY) {
        // 保存画笔状态
        ctx.save();
        // 设置箭头样式
        ctx.lineWidth = 2;
        ctx.strokeStyle="#000000";
        ctx.fillStyle="#FF0000";
        ctx.lineCap="round";
        ctx.lineJoin="round";
        ctx.shadowBlur=2;
        ctx.shadowColor= "rgba(0, 0, 0, 0.5)";

        // 计算向量及其长度
        var dx = toX - fromX;
        var dy = toY - fromY;
        var distance = Math.sqrt(dx*dx + dy*dy);

        // 计算箭头头部的终点坐标
        var headX = toX - dx / distance * 10;
        var headY = toY - dy / distance * 10;

        // 绘制箭身
        ctx.beginPath();
        ctx.moveTo(fromX, fromY);
        ctx.lineTo(headX, headY);
        ctx.stroke();

        // 绘制箭头头部
        ctx.beginPath();
        ctx.moveTo(toX, toY);
        ctx.lineTo(headX - dy / distance * 5, headY + dx / distance * 5);
        ctx.lineTo(headX + dy / distance * 5, headY - dx / distance * 5);
        ctx.closePath();
        ctx.fill();

        // 恢复画笔状态
        ctx.restore();
    }
    
    drawArrow(ctx, 50, 50, 150, 150);

    </script>

</html>