重新附加的Canvas元素保留内容

时间:2016-09-03 11:22:21

标签: javascript html5 dom canvas

Parser是一个能够在目标画布上绘制xml的模块。删除原始画布元素并附加干净画布后,画布将重置,但在进一步重新附加后,画布的内容将保持不变。



function setAttributes(elem, attrs) {
  for (var key in attrs) {
    elem.setAttribute(key, attrs[key]);
  }
}

var Parser = (function() {
  var cleanCanvas = (function() {
    var canvas = document.createElement("canvas");
    setAttributes(canvas, {
      "id": "canvas",
      "style": "border: 2px solid black",
      "width": "200px",
      "height": "200px"
    });
    return canvas;
  })();

  return {
    parseSVG: function(data, target) {
      lastTarget = $("#" + target).clone();
      var canvas = document.getElementById(target);
      var ctx = canvas.getContext('2d');

      var DOMURL = window.URL || window.webkitURL || window;

      var img = new Image();
      var svg = new Blob([data], {
        type: 'image/svg+xml;charset=utf-8'
      });
      var url = DOMURL.createObjectURL(svg);

      img.onload = function() {
        ctx.drawImage(img, 0, 0);
        DOMURL.revokeObjectURL(url);
      }

      img.src = url;
      var ctx = canvas.getContext('2d');
      var DOMURL = window.URL || window.webkitURL || window;

      var img = new Image();
      var svg = new Blob([data], {
        type: 'image/svg+xml;charset=utf-8'
      });
      var url = DOMURL.createObjectURL(svg);

      img.onload = function() {
        ctx.drawImage(img, 0, 0);
        DOMURL.revokeObjectURL(url);
      }

      img.src = url;
    },

    clearCanvas: function() {
      document.body.removeChild(document.getElementById("canvas"));
      document.body.appendChild(cleanCanvas);
    }
  }
})();

//Tried in console:

var data =
  '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
  '<foreignObject width="100%" height="100%">' +
  '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
  '<h1>blah</h1>' +
  '</div>' +
  '</foreignObject>' +
  '</svg>';

//Works properly
Parser.parseSVG(data, "canvas");
Parser.clearCanvas();

//Doesn't work properly
Parser.parseSVG(data, "canvas");
Parser.clearCanvas();
&#13;
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <canvas id="canvas" style="border: 2px solid black" width="200px" height="200px">
  </canvas>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="html2img.js"></script>
</body>

</html>
&#13;
&#13;
&#13;

为什么内容保持不变?

1 个答案:

答案 0 :(得分:0)

cleanCanvas在所有地方都是相同的参考,具有相同的上下文。这意味着:

// after appending cleanCanvas to body

alert(cleanCanvas === document.getElementById('canvas'));

/* --> true */

您可以改为使用cleanCanvas函数,这样您就可以通过调用它来重新生成它。

var getCleanCanvas = function() {
    var canvas = document.createElement("canvas");

    canvas.id = 'canvas';
    canvas.style.border = '2px solid black';

    setAttributes(canvas, {
        "width": "200px",
        "height": "200px"
    });

    return canvas;
};

现在:

document.body.appendChild(getCleanCanvas());