简体   繁体   中英

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. Let's say my Javascript code looks like this:

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 .

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

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