javascript - 调整窗口大小时防止 Canvas 清除

标签 javascript html canvas resize

我正在尝试创建一个在 Canvas 标签内绘制矩形的简单应用程序。我已将 Canvas 调整为全屏,但每当我调整视口(viewport)大小时,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;
      }

    };
  })();

最佳答案

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

关于javascript - 调整窗口大小时防止 Canvas 清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5517783/

相关文章:

javascript - Jquery日期选择器获取当前日期格式

javascript - 如何在两个 Canvas 中添加konva形状?

javascript - 您可以将 html 文件渲染到容器中吗?

javascript - 查询 JavaScript 对象分组依据

javascript - jQuery - 为什么 $(this) 在子作用域中不起作用?

html - 我们如何关闭默认的html5颜色选择器

javascript - 如何在 jquery 的 onchange radio 上运行两个函数?

javascript - div 内容中的文本显示不正确

javascript - 在 Canvas 上绘图

java - 获取 Canvas 中的鼠标位置(java)