Dynamically resize canvas window with javascript/jquery?

后端 未结 3 1049
野的像风
野的像风 2020-12-15 19:04

How can I resize a canvas with javascript/jquery?

Resizing using the css function and applying it to the canvas element just stretches the content as if you were str

3条回答
  •  不知归路
    2020-12-15 19:37

    Make a function that does the drawing, then re-draw whenever something changes that requires it (like a page resize, etc). Try it out

    Make sure you set the context.canvas.width/height, not CSS width/height. Also note that setting the size clears the canvas.

    How I would write it:

    (function(){
        var c = $("#canvas"), 
            ctx = c[0].getContext('2d');
    
        var draw = function(){
            ctx.fillStyle = "#000";
            ctx.fillRect(10,10,50,50);   
        };
    
        $(function(){
            // set width and height
             ctx.canvas.height = 600;
             ctx.canvas.width = 600;
            // draw
            draw();
    
            // wait 2 seconds, repeate same process
            setTimeout(function(){
                ctx.canvas.height = 400;
                ctx.canvas.width = 400;
                draw();
            }, 2000)
        });
    })();
    

提交回复
热议问题