2

If have an image which is 1024x1250 and a canvas element that is 600x800, I can draw the image to the canvas centered such that the canvas is essentially a smaller view port of the larger image. I then want to allow that center point to move, thus creating the illusion that the viewport is viewing a different portion of the image.

Right now I've done this in sort of a hokey way where I redraw the portion of the image I want to see to the canvas, but I get this feeling that this isnt optimal. Is there a way to render the whole image to the canvas and then somehow "transform" my current center point so this view shift happens behind the scenes hopefully in some native layer?

j03m
  • 5,195
  • 4
  • 46
  • 50

1 Answers1

6

You can add transformations to the context before drawing any image (rotation, scaling, translation...). What you need is the function context.translate(x,y).

Then, you only need to draw your image at (0,0)

For example, to display the bottom right portion of your image:

ctx.translate (-424, -450);
ctx.drawImage (image, 0, 0);

You can check this link https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Transformations to see a lot of examples on context transformation.

groovecoder
  • 1,551
  • 1
  • 17
  • 27
Luis Medel
  • 463
  • 2
  • 9