canvas绘画箭头

636 阅读1分钟

//绘画三角箭头

    /**
     * 
     * @param {*} ctx Canvas绘图环境
     * @param {*} fromX 起点坐标(也可以换成 p1 ,只不过它是一个数组)
     * @param {*} fromY 
     * @param {*} toX  终点坐标 (也可以换成 p2 ,只不过它是一个数组)
     * @param {*} toY 
     * @param {*} theta  三角斜边一直线夹角
     * @param {*} headlen 三角斜边长度
     * @param {*} width 箭头线宽度
     * @param {*} color 箭头颜色
     */
    drawArrow(ctx, fromX, fromY, toX, toY, theta, headlen, width, color) {
        var theta = theta || 30,
            headlen = headlen || 10,
            width = width || 1,
            color = color || '#2461EF',
            angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI,
            angle1 = (angle + theta) * Math.PI / 180,
            angle2 = (angle - theta) * Math.PI / 180,
            topX = headlen * Math.cos(angle1),
            topY = headlen * Math.sin(angle1),
            botX = headlen * Math.cos(angle2),
            botY = headlen * Math.sin(angle2);
        ctx.save();
        ctx.beginPath();
        var arrowX, arrowY;
        ctx.moveTo(fromX, fromY);
        ctx.lineTo(toX, toY);
        arrowX = toX + topX;
        arrowY = toY + topY;
        ctx.moveTo(arrowX, arrowY);
        ctx.lineTo(toX, toY);
        arrowX = toX + botX;
        arrowY = toY + botY;
        ctx.lineTo(arrowX, arrowY);
        ctx.strokeStyle = color;
        ctx.lineWidth = width;
        ctx.stroke();
        ctx.restore();
    }