使用javascript/jquery动态调整画布窗口的大小?

max*_*hud 18 javascript jquery html5 canvas

如何使用javascript/jquery调整画布大小?

使用css函数调整大小并将其应用于canvas元素只会拉伸内容,就像拉伸图像一样.

如果没有伸展,我该怎么做呢?

http://jsfiddle.net/re8KU/4/

Jos*_*ell 22

创建一个执行绘图的函数,然后在需要更改某些内容时重新绘制(如页面调整大小等).试试看

确保设置context.canvas.width/height,而不是CSS宽度/高度.另请注意,设置大小会清除画布.

我该怎么写呢:

(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)
    });
})();
Run Code Online (Sandbox Code Playgroud)


Kni*_*hts 10

 (function($) {  
        $.fn.extend({  
            //Let the user resize the canvas to the size he/she wants  
            resizeCanvas:  function(w, h) {  
                var c = $(this)[0]  
                c.width = w;  
                c.height = h  
            }  
        })  
    })(jQuery)
Run Code Online (Sandbox Code Playgroud)

使用我创建的这个小功能来处理随时随地调整大小.用这种方式 -

$("the canvas element id/class").resizeCanvas(desired width, desired height)
Run Code Online (Sandbox Code Playgroud)

  • 我把这两个答案结合起来,发挥了很大的作用!谢谢你们俩. (2认同)