【问题标题】:How to add a zoom feature with mouse to my canvas如何使用鼠标向我的画布添加缩放功能
【发布时间】:2018-04-01 23:21:49
【问题描述】:

我正在开发一个 web 应用程序,它包括我绘制函数图形的部分,坐标系由 Canvas 制作。问题是,我无法放大我的坐标系。我想让它能够放大和缩小+使用鼠标移动坐标系。 x 和 y 值也应在放大/缩小时增加/减少。

有人可以帮我解决这个问题吗?

我搜索了一些解决方案,但找不到任何有用的东西。这就是为什么我决定在这里问它。

这是我的代码:

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

我在一周前问了这个问题,但没有得到答案。 我希望有人可以帮助我

【问题讨论】:

标签: javascript html canvas html5-canvas


【解决方案1】:

onwheel 事件附加到函数并使用ctx.scale() 函数进行放大和缩小。

你可能想要做类似的事情

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);

确保它从中心缩放。

抱歉,我是用手机写的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-23
    • 2011-07-08
    • 2014-08-27
    • 1970-01-01
    • 2016-01-01
    • 2014-11-05
    • 2018-11-14
    • 1970-01-01
    相关资源
    最近更新 更多