如何在 javaScript 中将矩形居中?将矩形的 X 和 Y 位置作为矩形的中心

How do you center a rectangle in javaScript? Having the X and Y position of the rectangle being the center of the rectangle

如何在 javaScript 中使矩形居中?将矩形的 X 和 Y 位置作为矩形的中心。这是我的代码的粗略想法。

var cxt = canvas.getContext("2d");
var canvas = var canvas = document.getElementById("myCanvas");

function createSprite(x,y,width,height) {
 this.x=x;
 this.y=y;
 this.width=width;
 this.height=height;

 this.display(){
 
 cxt.beginPath();
 cxt.rect(this.x,this.y,this.width,this.height);
 cxt.fill();
 cxt.stroke();
 
 }

}

这是非常规的,但如果你真的想那样做就很简单:

var cxt = canvas.getContext("2d");
var canvas = var canvas = document.getElementById("myCanvas");

function createSprite(x,y,width,height) {
 this.x=x;
 this.y=y;
 this.width=width;
 this.height=height;

 this.display(){
 
 cxt.beginPath();
 cxt.rect(this.x - this.width / 2, this.y - this.height / 2,this.width,this.height);
 cxt.fill();
 cxt.stroke();
 
 }

}