Click here to Skip to main content
15,884,836 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
JavaScript
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();
}
Posted
Updated 7-Oct-14 1:06am
v2
Comments
Sergey Alexandrovich Kryukov 7-Oct-14 14:36pm    
Just use the debugger and check up all coordinates of all elements...
—SA

1 solution

A simple one line change
JavaScript
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();
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900