1

I have a canvas with a zoom function, but want to be able to keep my camera focus point on the same location when changing the zoom.

I already use translate to move the canvas content for the camera offsets, so it's a bit confusing how i can also include an origin for the scale aspect.

My draw code looks like this:

function draw(){
    ctx.clearRect(0,0,el.width,el.height);

    ctx.save();

    ctx.translate(0-(camera.x - el.width/2),0-(camera.y-el.height/2));          
    ctx.scale(scale,scale);

     //draw stuff here

    ctx.restore();     
}

The current translate is to make sure the camera (middle of the screen) is looking at the right place, but once I scale it, the camera is no longer focussed on the right place.

I have added a JSFiddle to see it in action http://jsfiddle.net/j2r1ysan/ the red dot is the camera's focus point, when you zoom in far enough the red dot becomes focused over the blue square but in reality thats not what it was looking at when the scale was at default. How can i correct for this?

Sir
  • 8,135
  • 17
  • 83
  • 146
  • http://stackoverflow.com/questions/27339747/zoom-and-pan-in-animated-html5-canvas – markE Oct 07 '15 at 20:37
  • @markE i have sinced solved the problem which only required one line of code changed, that link you provided seems a really messy way to do something quite simple =/ – Sir Oct 07 '15 at 21:40
  • Glad you got it sorted. :-) – markE Oct 07 '15 at 23:24

1 Answers1

0

I have since solved the problem by changing the math logic to this:

function draw(){
    ctx.clearRect(0,0,el.width,el.height);

    ctx.save();

    ctx.translate(el.width/2,el.height/2);          
    ctx.translate(-camera.x*scale,-camera.y*scale); 
    ctx.scale(scale,scale); 
     //draw stuff here

    ctx.restore();     
}

Demo: http://jsfiddle.net/5uhfg91e/

I hope this will help others in future!

Sir
  • 8,135
  • 17
  • 83
  • 146