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

新手上路,请多包涵

我正在尝试创建一个在 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;
      }

    };
  })();

原文由 alvincrespo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 373
2 个回答

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

原文由 Justin Pearce 发布,翻译遵循 CC BY-SA 2.5 许可协议

设置画布宽度属性将清除画布。

如果您调整样式宽度(例如 canvas.style.visibility ),它将缩放(通常不会以这种漂亮的方式)。

如果你想使画布更大但保持其中的元素不变,我建议将画布存储为图像 - 例如调用 toDataURL 方法来获取图像,然后将其绘制到使用 drawImage() 调整画布大小。

原文由 mcrider 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题