简体   繁体   English

在 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

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>

The fillRect function uses the parameters as follows: void ctx.fillRect(x, y, width, height); fillRect function 使用参数如下: 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 .因此,在您的情况下,您使用4020调用square function ,这将(根据您的函数)转换为坐标 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>

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM