25

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

Zelkins
  • 723
  • 1
  • 5
  • 22
Matt
  • 1,893
  • 11
  • 33
  • 57

4 Answers4

55

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/.

Mark Rhodes
  • 10,049
  • 4
  • 48
  • 51
  • @Mark this is nice answer. can you please help me in this http://stackoverflow.com/questions/17487277/rotating-2-images-on-canvas Thanks in advance:) – Beginner Jul 05 '13 at 12:17
8

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);
Andrei Nemes
  • 3,062
  • 1
  • 16
  • 22
  • That worked too, but I misformulated my question. But my question has been solved already. Thanks – Matt May 01 '13 at 12:34
1

Offset the origin (which is always 0,0 -- top left) by + (image.width / 2) and + (image.height / 2) to start drawing in the centre of the canvas.

drawImage(image, image.width/2, image.height/2)
Glitch Desire
  • 14,632
  • 7
  • 43
  • 55
  • That worked too, but I misformulated my question. But my question has been solved already. Thanks! – Matt May 01 '13 at 12:33
0

If you want it to be in the center and you are rescaling the image, it scales down from the top corner but the center point stays the same. If you resize the image with JavaScript, you should not do that, instead just edit the image to be smaller/bigger.