Duncan
Duncan

Reputation: 3

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

How do you center a rectangle in javaScript? Having the X and Y position of the rectangle being the center of the rectangle. This is a rough idea for my code.

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();
 
 }

}

Upvotes: 0

Views: 523

Answers (1)

see sharper
see sharper

Reputation: 12035

It's unconventional, but simple if you really want to do it that way:

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();
 
 }

}

Upvotes: 1

Related Questions