在 html canvas 上,我试图在特定点绘制一个正方形,但如果 x 和 y 不相同,它会膨胀和扭曲

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

我弄乱了变量(在 + 和 - 之间移动等),但无论我做什么,它总是不断拨号。

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>

fillRect函数使用参数如下:void ctx.fillRect(x, y, width, height);

因此,在您的情况下,您使用 4020 调用 square 函数,这将(根据您的函数)转换为坐标 x = 30 和 y = 10,宽度为 50,高度为 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>

如果你想要一个正方形,你应该这样做:

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>