简体   繁体   English

如何在画布上缩放?

[英]How do I zoom on a canvas?

I'm fairly new to Javascript and HTML5, and I'm trying to figure out how to zoom on a canvas. 我是Java和HTML5的新手,我试图弄清楚如何在画布上缩放。 Let's say my Javascript code looks like this: 假设我的Javascript代码如下所示:

window.addEventListener('load', function() {
            var theCanvas = document.getElementById('myCanvas');
            theCanvas.style.border = "black 1px solid";
            if(theCanvas && theCanvas.getContext) {
                var context = theCanvas.getContext('2d');

                if(context) {
                    var x = 10;
                    var y = 10;
                    var z = 255;
                    var color = "rgb(0," + z + ",0)";
                    context.fillStyle = "rgb(100,0,0)";
                    for(var y = 0; y <= 290; y += 10) {

                        for(var x = 0; x <= 290; x += 10) {
                            if(z >= 1) {
                                z -= 1;
                            }
                            color = "rgb(0," + z + ",0)";

                            if(x % 20 === 0) {
                                context.fillStyle = color;
                            } else {
                                context.fillStyle = color;
                            }
                            context.fillRect(x, y, 10, 10);
                        }
                    }

                }

            }
        }, false);

In summary, this code just fills the canvas with tiled rectangles of changing color. 总而言之,此代码仅用变化颜色的平铺矩形填充画布。 But how would one go about zooming in and out on something like this? 但是,如何放大和缩小这种东西呢?

You'll want the scale method of context . 您将需要contextscale方法。

And note that, once you've drawn something on the canvas, it can't really be zoomed or scaled — you've got to re-draw the entire canvas at the new "zoom level". 请注意,一旦在画布上绘制了某些内容,就无法真正对其进行缩放或缩放-您必须在新的“缩放级别”上重新绘制整个画布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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