I have a Canvas that's 300x300 and an image that 150x150.
How can I draw this image in the center of this Canvas. What do i write in context.translate and context.drawImage?
On what browsers will this work?
I have a Canvas that's 300x300 and an image that 150x150.
How can I draw this image in the center of this Canvas. What do i write in context.translate and context.drawImage?
On what browsers will this work?
Share Improve this question edited Dec 16, 2011 at 4:14 Russ T asked Dec 16, 2011 at 4:04 Russ TRuss T 471 silver badge5 bronze badges2 Answers
Reset to default 3For argument's sake, let's imagine your image is a rectangle.
ctx.fillRect(
(canvasWidth - width) / 2,
(canvasHeight - height) / 2,
width,
height
);
jsFiddle.
The same form of calculations apply.
the centre of the image should be placed at 150,150. the top left of the image, which is often the point used to draw things, should be places at (150-150/2),(150-150/2)
assuming that 0,0
is the top left corner. More generally top left should be at ((W-w)/2),((H-h)/2)
where W and H are the width and height of the canvas and w and h are the width and height of the image to be drawn.
(sorry if you were asking 'how do I draw an image on a canvas')