HTML canvas - drawing disappear on resizing

前端 未结 7 1334
自闭症患者
自闭症患者 2020-12-03 17:08

I have created a basic shape in HTML canvas element which works fine.

The problem occurs when I resize the canvas, all the drawing in the canvas disappears. Is this

7条回答
  •  粉色の甜心
    2020-12-03 17:51

    I had the same problem when I had to resize the canvas to adjust it to the screen. But I solved it with this code:

    var c = document.getElementById('canvas');
    ctx = c.getContext('2d');
    ctx.fillRect(0,0,20,20);
    // Save canvas settings
    ctx.save();
    // Save canvas context
    var dataURL = c.toDataURL('image/jpeg');
    // Resize canvas
    c.width = 50;
    c.height = 50;
    // Restore canvas context
    var img = document.createElement('img');
    img.src = dataURL;
    img.onload=function(){
      ctx.drawImage(img,20,20);
    }
    // Restote canvas settings
    ctx.restore();

提交回复
热议问题