Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 ?

What I have tried:

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:

HTML
<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>
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900