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>
4

1 回答 1

1

您不能将 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>
于 2020-04-07T08:57:59.207 回答