user2170969
user2170969

Reputation:

Issue while drawing line over HTML5 Canvas

<body>
    <canvas id="myCanvas" style="border:1px solid #000000; width: 800px;height:800px">
    </canvas>
</body>

I have a canvas defined like this. And on view ready I am drawing an arrow over the canvas graphics.

window.onload = function() {

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "#000000";
    ctx.fillRect(0, 0, 800, 800);
    drawArrow(100, 100, 100, 20, ctx);
};



function drawArrow(x, y, w, h, ctxt) {

    var headWidth = 10;
    ctxt.beginPath();
    ctxt.strokeStyle = "#FF0";
    ctxt.moveTo(x, y + (h / 2));
    ctxt.lineTo(x + w, y + (h / 2));

    //To Draw Arrow Head
    ctxt.moveTo((x + w) - headWidth, y + (h / 2));
    ctxt.lineTo((x + w) - (2 * headWidth), y);
    ctxt.lineTo((x + w), y + (h / 2));
    ctxt.lineTo((x + w) - (2 * headWidth), y + h);
    ctxt.lineTo((x + w) - headWidth, y + (h / 2));

    //To Draw Arrow Tail
    ctxt.moveTo(x + (headWidth), y + (h / 2));
    ctxt.lineTo(x, y);
    ctxt.lineTo(x + (2 * headWidth), y + (h / 6));
    ctxt.lineTo(x + (2 * headWidth), y + (h * (3 / 4)));
    ctxt.lineTo(x, y + h);
    ctxt.lineTo(x + headWidth, y + (h / 2));

    ctxt.lineWidth = 1;
    ctxt.stroke();
} 

Even though I set ctxt.lineWidth to 1, the line width is not seems like 1 and also the lines are some what stretched. Can anybody point out what I am doing wrong?

Upvotes: 2

Views: 399

Answers (3)

Triode
Triode

Reputation: 11359

<canvas id="myCanvas" width="800" height="800" style="border:1px solid #000000;">
</canvas>

Even you an set the width and height like this, it will also work.

Upvotes: 1

Aaron Blenkush
Aaron Blenkush

Reputation: 3059

You have to specify the coordinates "in between pixels". For example, if you draw a line from [0,0] to [10,0], you'll get a wider line than if you draw from [0.5,0.5] to [10.5,0.5].

Upvotes: 0

Loktar
Loktar

Reputation: 35309

Its due to you setting the width and height via CSS. Changing the width and height via CSS will change the size of the canvas element, but not the pixel density. In order to do that you must set the .width and .height property on the canvas element directly.

Change your onload to the following, and remove the width and height styling on the element.

Live Demo

window.onload = function() {

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    // canvas width and height set here.
    c.width = 800;
    c.height = 800;

    ctx.fillStyle = "#000000";
    ctx.fillRect(0, 0, 800, 800);
    drawArrow(100, 100, 100, 20, ctx);
};

Upvotes: 1

Related Questions