克隆HTML画布及其内容

问题描述 投票:0回答:1

我有一块HTML代码和一个画布,我想通过单击按钮来复制它。到目前为止,我已经尝试过此代码,但是对于缺少的内容我一无所知。如果您可以包括任何一段代码,对我来说都是非常有用的,因为我是一个初学者谢谢

 <canvas id="myCanvas" width="800px" height="800px"></canvas>

    <script>
      var oldCnv = document.getElementById("myCanvas");

      function cloneCanvas(oldCanvas) {
        //create a new canvas
        var newCanvas = document.createElement("canvas");
        var context = newCanvas.getContext("2d");

        //set dimensions
        newCanvas.width = oldCanvas.width;
        newCanvas.height = oldCanvas.height;

        //apply the old canvas to the new one
        context.drawImage(oldCanvas, 0, 0);

        //return the new canvas
        return newCanvas;
        //append the new canvas on the page
        document.body.appendChild(newCanvas);
      }
    </script>
    <button onclick="cloneCanvas(oldCnv)">add canvas</button>
javascript html html5-canvas copy-paste
1个回答
0
投票

您无法在onclick操作中将参数oldCnv传递给该函数。除此之外,在您return newCanvas之后,document.body.appendChild(newCanvas)将不会被调用。

以下将起作用。使用此代码:

 <canvas id="myCanvas" width="800px" height="800px"></canvas> 
   <script>
      var oldCanvas = document.getElementById("myCanvas");

      function cloneCanvas() {
        //create a new canvas
        var newCanvas = document.createElement("canvas");
        var context = newCanvas.getContext("2d");

        //set dimensions
        newCanvas.width = oldCanvas.width;
        newCanvas.height = oldCanvas.height;

        //apply the old canvas to the new one
        context.drawImage(oldCanvas, 0, 0);

        //return the new canvas
        //append the new canvas on the page
        document.body.appendChild(newCanvas);
      }
    </script>
    <button onclick="cloneCanvas()">add canvas</button>
© www.soinside.com 2019 - 2024. All rights reserved.