Salvius
Salvius

Reputation: 1253

Centering shapes in HTML canvas

I have an HTML canvas with a rectangle like this:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();

Is it possible to center that rectangle in the canvas with css? I want it to stay centered regardless of what the width of the canvas is.

Upvotes: 3

Views: 692

Answers (2)

Jay Rathod
Jay Rathod

Reputation: 51

An easier way to center the rectangle on canvas:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var width = 130, height = 80;//Dimensions of rectangle
var x = canvas.Width/2, y = canvas.Height/2;//Center coordinates of rectangle 
ctx.rect(x - width/2, y - height/2, width, height);
ctx.stroke();

Refer this for the pictorial representation

Upvotes: 3

Quentin
Quentin

Reputation: 943569

No.

The canvas is just a bunch of pixels. There are no elements for CSS to influence.

If you want to centre something inside the canvas, then you have to pick the right place the put the pixels you are colouring in the first place.

You might be better off using SVG for your graphics, especially if they are simple shapes like rectangles.

Upvotes: 3

Related Questions