How to resize html canvas element?

后端 未结 7 1844
慢半拍i
慢半拍i 2020-11-29 01:34

I have a canvas element defined statically in the html with a width and height. If I attempt to use JavaScript to resize it dynamically (setting a new width and height - eit

7条回答
  •  情深已故
    2020-11-29 02:35

    I just had the same problem as you, but found out about the toDataURL method, which proved useful.

    The gist of it is to turn your current canvas into a dataURL, change your canvas size, and then draw what you had back into your canvas from the dataURL you saved.

    So here's my code:

    var oldCanvas = canvas.toDataURL("image/png");
    var img = new Image();
    img.src = oldCanvas;
    img.onload = function (){
        canvas.height += 100;
        ctx.drawImage(img, 0, 0);
    }
    

提交回复
热议问题