Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw images on in the middle of a canvas

Tags:

I'm making a photogallery, but all my images are painted in the origin (0,0).

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

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

Thanks for helping me out!

UPDATE

I might have formed my question a bit wrong. What I mean is: I want the middle of my image to be in the middle of my canvas, not the top corner of the image.

Sorry for that

Edit: typo

Edit2: typo

like image 291
Matt Avatar asked May 01 '13 12:05

Matt


People also ask

Can you draw on an image in canvas?

The function we use for drawing an image onto a canvas is the drawImage() function. This function draws an image, canvas, or video onto the canvas. It can also draw parts of an image, and/or increase/reduce the image size.

Which method is used to draw an image on a canvas?

The drawImage() method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size. Note: You cannot call the drawImage() method before the image has loaded.


2 Answers

If you supply the x, y position like so:

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 is available at: http://jsfiddle.net/VPLZc/2/.

like image 129
Mark Rhodes Avatar answered Sep 25 '22 00:09

Mark Rhodes


If you want to draw it dead on into the centre, you need to know the image width and height. It becomes easy afterwards:

//var canvas = document.getElementById("yourCanvasElementID"); var img = arrPhoto[currentIndex]; canvasContent.drawImage(img, (canvas.width-img.width)/2, (canvas.height-img.height)/2); 
like image 36
Andrei Nemes Avatar answered Sep 24 '22 00:09

Andrei Nemes