Graphic made with imperfection Javascript canvas

2

I made a normal Cartesian plan here on a canvas, but with a problem, the graph is not perfectly centered and this is bothering me a lot, I know I can change the position manually in code, but the question is: By that 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 get the height divided by 2 and the width tbm, I already tried both with the client when with the offset and both have the same imprecision. Why does it happen? Thanks

I tested using the raw values putting them directly into the function and it worked right, the question is, why when I pull the imprecision?

    
asked by anonymous 07.11.2015 / 22:57

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 clientWidth and clientHeight properties depending on the browser include element padding, and are originally MS implementations .

See more details on clientWidth and width in MDN.     

08.11.2015 / 19:01