简体   繁体   中英

How to add a zoom feature with mouse to my canvas

I'm working on a webapp and it includes one part where I draw the graph of a function, the coordinate system is made by Canvas. The problem is, I can not zoom into my coordinate system. I want to make it able to zoom in and out + moving the coordinate system using the mouse. The x and y values should also increase/decrease while zooming in/out.

Could somebody help me with this ?

I searched for some solutions, but I couldn't find anything useful. That's why I decided to ask it here.

Here are my codes:

<canvas id="myCanvas" width="300" height="300" style="border:1px solid #d3d3d3;"></canvas>

<!--Canva startup-->
<script>
    // Setup values
    var height = 300;
    var width = 300;
    var zoomFactor = 15;

    // --------
    var c = document.getElementById("myCanvas");
    var xZero = width / 2;
    var yZero = height / 2;
    var ctx = c.getContext("2d");

    // Draw Cord-System-Grid
    ctx.beginPath();
    ctx.moveTo(xZero, 0);
    ctx.lineTo(xZero, height);
    ctx.strokeStyle = "#000000";
    ctx.stroke();
    ctx.moveTo(0, yZero);
    ctx.lineTo(width, yZero);
    ctx.strokeStyle = "#000000";
    ctx.stroke();
    ctx.beginPath();

    // Draw Numbers
    ctx.font = "10px Georgia";
    var heightTextX = yZero + 10;
    for(var i = 0; i < width; i = i + width / 10) {
        var numberX = (-1 * xZero / zoomFactor) + i / zoomFactor;  
        ctx.fillText(numberX, i, heightTextX);
    }

    var heightTextY = yZero + 10;
    for(var n = 0; n < height; n = n + height / 10) {
        var numberY = (-1 * yZero / zoomFactor) + n / zoomFactor;
        if(numberY !== 0)
            ctx.fillText(numberY * -1, heightTextY, n);
    }

</script>

I asked this question before a week, but couldn't get an answer. I hope somebody can help me

Attach the onwheel event to a function and use the ctx.scale() function to zoom in and out.

You will probably want to do something like

let canvas = document.getElementById('myCanvas');
ctx.translate(canvas.width/2, canvas.height/2);
ctx.scale(zoomFactor, zoomFactor);
ctx.translate(-canvas.width/2, -canvas.height/2);

To make sure it zooms from the center.

Sorry for any minor errors I'm writing this from my phone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM