Resize HTML5 canvas element

前端 未结 3 1598
温柔的废话
温柔的废话 2021-01-07 01:48

How can I achieve, so that the HTML5 canvas element ist resizeable?

I would like to implement this element so that you can scale it in any size. The event of the sca

3条回答
  •  猫巷女王i
    2021-01-07 01:54

    Setting a canvas's width or height properties has the effect of clearing the canvas. Even canvas.width = canvas.width; will cause you to lose everything in the canvas. Sometimes this is desirable, but in your case it probably isn't.

    What you will probably need to do is something like this

     var myCanvas = document.getElementById('myCanvas');
     var tempCanvas = document.createElement('canvas');
     tempCanvas.width = myCanvas.width;
     tempCanvas.height = myCanvas.height;
    
     // save your canvas into temp canvas
     tempCanvas.getContext('2d').drawImage(myCanvas, 0, 0);
    
     // resize my canvas as needed, probably in response to mouse events
     myCanvas.width = newWidth;
     myCanvas.height = newHeight;
    
     // draw temp canvas back into myCanvas, scaled as needed
     myCanvas.getContext('2d').drawImage(tempCanvas, 0, 0, tempCanvas.width, tempCanvas.height, 0, 0, myCanvas.width, myCanvas.height);
    

    In most browsers, the scaling will be done with a bicubic scaling algorithm, causing it to get blurry. In some cases you can set a CSS property to cause nearest neighbor on the canvas if you want, but browser support for this is very spotty right now. You can instead manually do a nearest neighbor scale , as this question shows: How to stretch images with no antialiasing

    Alternative CSS Approach

    Another approach is to scale the canvas using CSS. In Chrome/Safari/IE you can just do:

    
    

    In Firefox, you can use a scale transform to achieve the same effect:

    
    

    In many ways this approach is easier, but it comes with its own little gotchas and browser specific quirks.

提交回复
热议问题