Search code examples
javascripthtmlcanvasvarrect

On an html canvas, I am trying to draw a square at a specific point, but if the x and y aren't the same, it dilates and distorts


I have messed with the variables (shifting between + and -, etc), but it always keeps dialating, whatever I do.

var c = document.getElementById("mycanvas").getContext("2d");
c.fillStyle = "blue";
c.fillRect (0,0,500,350);

function square(x,y) {
    var leftX = (x - 10)
    var leftY = (y - 10)
    var rightX = (x + 10)
    var rightY = (y + 10)
    c.fillStyle = "red";
    c.fillRect (leftX,leftY,rightX,rightY)
}

square(40,20);
<canvas id="mycanvas" width="1000" height="1000"></canvas>


Solution

  • The fillRect function uses the parameters as follows: void ctx.fillRect(x, y, width, height);

    So in your case you're calling the square function with 40 and 20 which will translate (according to your function) to the coordinates x = 30 and y = 10 with a width of 50 and a height of 30.

    var c = document.getElementById("mycanvas").getContext("2d");
    c.fillStyle = "blue";
    c.fillRect (0,0,500,350);
    
    function square(x,y) {
        var leftX = (x - 10); // x = 30
        var leftY = (y - 10); // y = 10
        var width = (x + 10); // width = 50
        var height = (y + 10); // height = 30
        c.fillStyle = "red";
        c.fillRect (leftX,leftY,width,height);
    }
    
    square(40,20);
    <canvas id="mycanvas" width="1000" height="1000"></canvas>

    If you want a square you should do something like this:

    var c = document.getElementById("mycanvas").getContext("2d");
    c.fillStyle = "blue";
    c.fillRect (0,0,500,350);
    
    function square(x,y) {
        var leftX = (x - 10); // x = 30
        var leftY = (y - 10); // y = 10
        c.fillStyle = "red";
        c.fillRect (leftX,leftY,20,20);
    }
    
    square(40,20);
    <canvas id="mycanvas" width="1000" height="1000"></canvas>