调整窗口大小时防止画布清除

alv*_*spo 23 html5 canvas clear redraw

我正在尝试创建一个在Canvas标签内绘制矩形的简单应用程序.我已经将Canvas调整为全屏,但每当我调整视口大小时,Canvas都会清除.我试图阻止它清除,只是保留其中的内容.有任何想法吗?

http://mediajux.com/experiments/canvas/drawing/

谢谢!

      /*
      * This is the primary class used for the application
      * @author Alvin Crespo
      */
      var app = (function(){

        var domBod          = document.body;
        var canvas          = null;
        var canvasWidth     = null;
        var canvasHeight     = null;

        return {

          //Runs after the DOM has achieved an onreadystatechange of "complete"
          initApplication: function()
          {
            //setup envrionment variables
            canvas = document.getElementById('canvas') || null;

            //we need to resize the canvas at the start of the app to be the full window
            this.windowResized();

            //only set the canvas height and width if it is not false/null
            if(canvas)
            {
              canvasWidth = canvas.offsetWidth;
              canvasHeight = canvas.offsetHeight;        
            }

            //add window events
            window.onresize = this.windowResized;   

            circles.canvas = canvas;
            circles.canvasWidth = canvasWidth;
            circles.canvasHeight = canvasHeight;
            circles.generateCircles(10);  

            setInterval(function(){
                circles.animateCircles();
            }, 50);   
          },

          /**
          * Executes Resizing procedures on the canvas element
          */
          windowResized: function()
          {
            (this.domBod === null) ? 'true' : 'false';
            try{
              console.log(canvas);
              canvas.setAttribute('width', document.body.clientWidth);
              canvas.setAttribute('height', document.body.clientHeight);        
            }catch(e) {
              console.log(e.name + " :: " + e.message);
            }
          },

          /**
          * Returns the canvas element 
          * @returns canvas
          */
          getCanvas: function()
          {
            return canvas;
          }

        };
      })();
Run Code Online (Sandbox Code Playgroud)

mcr*_*der 15

设置画布宽度属性将清除画布.如果您调整样式宽度(例如canvas.style.visibility),它将缩放(通常不会以这种漂亮的方式).如果你想让画布更大但是按原样保留元素,我建议将画布存储为图像 - 例如调用toDataURL方法获取图像,然后使用drawImage()将其绘制到调整大小的画布上.

  • 令人难以置信的是,我不知道更改高度或宽度属性会清除画布! (2认同)
  • 当你可以[简单地使用](/sf/answers/4908741841/) `getImageData()`/`putImageData()`时,为什么还要费心使用`toDataURL`呢? (2认同)

bra*_*sch 7

这是我用JS3解决这个问题的方法.

在内部,我将主画布和上下文分别存储为_canvas和_context.

function resize(w, h){
// create a temporary canvas obj to cache the pixel data //
    var temp_cnvs = document.createElement('canvas');
    var temp_cntx = temp_cnvs.getContext('2d');
// set it to the new width & height and draw the current canvas data into it // 
    temp_cnvs.width = w; 
    temp_cnvs.height = h;
    temp_cntx.fillStyle = _background;  // the original canvas's background color
    temp_cntx.fillRect(0, 0, w, h);
    temp_cntx.drawImage(_canvas, 0, 0);
// resize & clear the original canvas and copy back in the cached pixel data //
    _canvas.width = w; 
    _canvas.height = h;
    _context.drawImage(temp_cnvs, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)

JS3还提供了一个autoSize标志,它会自动将画布调整大小到浏览器窗口或其父div的尺寸.


小智 7

我解决这个问题的一种方法是:

const canvas = document.getElementById('ctx')
const ctx = canvas.getContext('2d')
var W = canvas.width, H = canvas.height
function resize() {
    let temp = ctx.getImageData(0,0,W,H)
    ctx.canvas.width = window.innerWidth - 99;
    ctx.canvas.height = window.innerHeight - 99;
    W = canvas.width, H = canvas.height
    ctx.putImageData(temp,0,0)
}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是,缩小时您会丢失画布外的数据


Dim*_*ash 5

使用样式(css)设置画布大小,并且不要更改属性。

调整为全屏尺寸后

画布将被调整大小并且不会被清除,但是将被缩放,以防止缩放-您需要在调整大小后重新缩放,这是数学公式:

var oldWidth    =  $("canvas").css("width").replace("px", "");
var oldHeight   = $("canvas").css("height").replace("px", "");  

$("canvas").css({ 
            "width" : window.innerWidth, 
            "height": window.innerHeight
        }); 



var ratio1 =  oldWidth/window.innerWidth;
var ratio2 =  oldHeight/window.innerHeight;



canvas.ctx.scale(ratio1, ratio2);
Run Code Online (Sandbox Code Playgroud)

请注意,我是从代码中复制粘贴的,并快速对id和vars名称进行了一些更改,因此可能会有一些小的问题,例如“ canvas.ctx”或dom调用。


Jus*_*rce 1

我相信您已经实现了一个监听器,用于在该监听器触发时调整屏幕大小并重新绘制画布内容。

  • 我看到您正在调整画布大小,但在调整画布大小后您没有执行任何绘制操作。添加一个执行绘图的函数,并在调用更改高度和宽度属性后调用它。 (3认同)