在缩放后在画布上绘制箭头 [英] Drawing arrow on canvas after zooming

查看:110
本文介绍了在缩放后在画布上绘制箭头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HTML5画布允许用户在其上绘制对象。我新添加了放大功能,一切正常,除非在向画布添加缩放后箭头线被正确绘制但箭头在画布上放错位置。

以下是绘制线条和箭头的功能。

I am using HTML5 canvas to allow user to draw objects on it.I have newly added zoom in functionality to it,everything works fine except after adding zooming to canvas the line of arrow get drawn properly but arrow head gets misplaced on canvas.
Below are the functions for drawing line and arrow head.

function DrawLine(ctx, mouseDownX, mouseDownY, mouseX, mouseY, color, diffX, diffY, isArrow) {
    writeLog();
    ctx.beginPath();
    ctx.strokeStyle = color;

    //    if (window.isZoomdraw) {
    ctx.save();
    ctx.translate(cw / 2, ch / 2);
    ctx.scale(scale, scale);
    //    }

    ctx.moveTo(mouseDownX + diffX, mouseDownY + diffY);
    ctx.lineTo(mouseX + diffX, mouseY + diffY);
    ctx.stroke();

    //    if (window.isZoomdraw)
    ctx.restore();

    if (isArrow) {

        var radianAngle = Math.atan((mouseY - mouseDownY) / (mouseX - mouseDownX));
        radianAngle += ((mouseX > mouseDownX) ? 90 : -90) * Math.PI / 180;
        drawArrowHead(ctx, mouseX + diffX, mouseY + diffY, radianAngle, strokeColor);
    }

}

function drawArrowHead(ctx, x, y, radians, strokeColor) {

    var arrowWidth = ctx.lineWidth / 3;
    ctx.save();
    ctx.strokeStyle = "white";
    ctx.beginPath();
    ctx.translate(x, y);
    ctx.scale(scale, scale);
    ctx.rotate(radians);
    ctx.moveTo(0, 0);
    ctx.lineTo(16 * arrowWidth, 10 * arrowWidth);
    ctx.lineTo(-16 * arrowWidth, 10 * arrowWidth);
    ctx.closePath();
    ctx.restore();
    ctx.fillStyle = "white";
    ctx.fill();
}

推荐答案

一个简单的换行

A simple one line change
function drawArrowHead(ctx, x, y, radians, strokeColor) {
 
    var arrowWidth = ctx.lineWidth / 3;
    ctx.save();
    ctx.strokeStyle = "white";
    ctx.beginPath();
    ctx.translate(x+(cw / 2), y+(ch / 2));
    ctx.scale(scale, scale);
    ctx.rotate(radians);
    ctx.moveTo(0, 0);
    ctx.lineTo(16 * arrowWidth, 10 * arrowWidth);
    ctx.lineTo(-16 * arrowWidth, 10 * arrowWidth);
    ctx.closePath();
    ctx.restore();
    ctx.fillStyle = "white";
    ctx.fill();
}


这篇关于在缩放后在画布上绘制箭头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆