Graphic made with imperfection Javascript canvas

Asked

Viewed 159 times

2

Guys I made a normal Cartesian plan here on a canvas, but with a problem, the chart is not perfectly centered and this is bothering me a bit, I know q I can change the position manually in code, but the question is: Why the graph is decentralized?

Here is the JS code:

window.onload = function () {
    var contex = document.getElementById("grafico").getContext("2d");
    contex.moveTo(0, document.getElementById("grafico").clientHeight/2);
    contex.lineTo(document.getElementById("grafico").clientWidth, document.getElementById("grafico").clientHeight/2);
    contex.moveTo(document.getElementById("grafico").clientWidth/2, 0);
    contex.lineTo(document.getElementById("grafico").clientWidth/2, document.getElementById("grafico").clientHeight);
    contex.stroke();
}

in this code I take the height divided by 2 and the width tbm, I have tried both with the client and with the offset and both present the same inaccuracy. Why does this happen? Thank you

I tested using the raw values by putting them directly in the function and there it worked right, the question is, why when I pull the inaccuracy?

1 answer

3


The ideal would be to use the property width and height instead of clientWidth and clientHeight:

window.onload = function () {
    var contex = document.getElementById("grafico").getContext("2d");
    contex.moveTo(0, document.getElementById("grafico").height/2);
    contex.lineTo(document.getElementById("grafico").width,
       document.getElementById("grafico").height/2);
    contex.moveTo(document.getElementById("grafico").width/2, 0);
    contex.lineTo(document.getElementById("grafico").width/2,
       document.getElementById("grafico").height);
    contex.stroke();
}

The properties clientWidth and clientHeight depending on the browser include the element padding, and are originally MS implementations.

See more details about the clientWidth and the width on MDN.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.