javascripthtmlmobilecanvaszooming

Canvas Zooming in HTML5 mobile


I'm currently making a game, and I need to zoom into canvas.

I've read a lot about how to zoom in canvas, with the ctx.scale() method, the thing is, I want to zoom with both fingers.

I already have the zoom, but it's zooming from the top/left canvas, and not on the middle of my fingers.

I have the middle point between finger 1 and finger 2, but I don't know how to zoom into that specific middle point !

This example pretty much sums up what I need (I just need the zoom) : Zoom Canvas to Mouse Cursor

It's working really fine, but with the wheel !

If any of you as any ideas, I'd be really glad to talk ! :)

Thanks everyone !


Solution

  • If you have the center point from which you want to scale, you could use the translation tool provided by the CanvasRenderingContext2D:

    void translate(
       in float x,
       in float y
    );
    

    So when you have your canvas context in a variable ctx do

    ctx.translate(x, y);
    

    And then

    ctx.scale(x, y);
    

    The ctx.translate(x, y) places the origin to x, y coordinates. By default, the origin of the CanvasRenderingContext2D is at 0, 0 (http://www.w3.org/TR/2dcontext/) so that's why the scaling originates from the top left corner.

    Source https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D#translate()