Draw images in the middle of the canvas

I make a photo gallery, but all my images are painted at the origin (0,0).

canvasContent.drawImage(arrPhoto[currentIndex], 0, 0); 

How can I make sure that my images are drawn in the middle of the canvas?

Thanks for helping me!

UPDATE

I might ask my question a little wrong. I mean: I want the middle of my image to be in the middle of my canvas, and not in the upper corner of the image.

Sorry for this

Edit: typo

Edit2: typo

+8
javascript html image canvas
source share
3 answers

If you set the x, y position as follows:

 var image = arrPhoto[currentIndex]; canvasContent.drawImage(image, canvas.width / 2 - image.width / 2, canvas.height / 2 - image.height / 2 ); 

then it should appear in the center. An example of this in action can be found at: http://jsfiddle.net/VPLZc/2/ .

+22
source share

If you want to draw it in the center, you need to know the width and height of the image. After that it becomes easier:

 //var canvas = document.getElementById("yourCanvasElementID"); var img = arrPhoto[currentIndex]; canvasContent.drawImage(img, (canvas.width-img.width)/2, (canvas.height-img.height)/2); 
+3
source share

Move the origin (always 0,0 - top left) to + (image.width / 2) and + (image.height / 2) to start drawing in the center of the canvas.

 drawImage(image, image.width/2, image.height/2) 
+1
source share

All Articles