Search code examples
javascriptcanvaszoomingcenter

Apply zoom in center of the canvas


I need to apply zoom to the javascript canvas which I have badly accomplished by using the following line of code:

ctx.scale(2,2) //doubles everything's size

Instead of zooming, its obviously doubling the size of the canvas and all of its elements. I'd be okay with this if I got it working like the image below shows:

enter image description here

Any ideas on how I could accomplish what is depicted in the picture above? I'm not using any external libraries hence making this so difficult. Thanks.


Solution

  • You can translate the context by half the canvas size using ctx.translate()

    EDIT :

    var zoomfactor = 2; //set whatever you want as zoom factor
    ctx.transform(zoomfactor,0,0,zoomfactor,-(zoomfactor-1)*canvas.width/2,-(zoomfactor-1)*canvas.height/2)