Search code examples
javascriptalgorithmhtml5-canvaszoomingpixi.js

algorithmic Zoom calculation for canvas


Would anyone have the right math formula to calculate the zoom in a canvas game? I need one based on the mouse position.

the zoom scale the _tilemap, but i need a math formula that allow to scale base on mouse position.

const SM_S = SceneManager._scene;
const mapZoom = SM_S._spriteset._tilemap.scale;
    function wheel_(event) {//TODO: zoom system
        if(event.wheelDeltaY>0){
            mapZoom.x+=0.05;
            mapZoom.y+=0.05;
            $gameMap._displayX+=0.05
            dX+=0.05;
        }else{
            mapZoom.x-=0.05;
            mapZoom.y-=0.05;
            $gameMap._displayX-=0.05
            dX-=0.05;
        }
    };

the update position

const editorTiker = new PIXI.ticker.Ticker().add((delta) => {
    document.title = `(mX: ${mX})  (mY: ${mY}) | (dX: ${~~dX}) (dY: ${~~dY})`;
    if(scrollAllowed){
        let scrolled = false;
        (mX<20 && (dX-=scrollF) || mX>sceneX-20 && (dX+=scrollF)) && (scrolled=true);
        (mY<20 && (dY-=scrollF) || mY>sceneY-20 && (dY+=scrollF)) && (scrolled=true);
        scrolled && (scrollF+=0.01) || (scrollF=0.01) ;
    }
    $gameMap._displayX += ((dX-$gameMap._displayX)/scrollSpeed);
    $gameMap._displayY += ((dY-$gameMap._displayY)/scrollSpeed);
});

Solution

  • solved , i use pivot and memory slot

    let memCoord = new PIXI.Point(), memCoord2 = new PIXI.Point(); // for control zoom memory
        function wheel_(event) {
            setMouseXY(); // get mouse xy in canvas
            const pos = new PIXI.Point(mX,mY);
            SM_S._spriteset._tilemap.toLocal(pos, null, memCoord);
            if(event.wheelDeltaY>0){
                mapZoom.x+=0.1,mapZoom.y+=0.1
            }else{
               if(mapZoom.x>0.3){
                    mapZoom.x-=0.1, mapZoom.y-=0.1;
               };
            };
            SM_S._spriteset._tilemap.toLocal(pos, null, memCoord2);
            $gameMap._displayX -= (memCoord2.x - memCoord.x)/48;
            $gameMap._displayY -= (memCoord2.y - memCoord.y)/48;
            dX = +$gameMap._displayX;
            dY = +$gameMap._displayY;
        };