Search code examples
javascripthtmlhtml5-canvascopy-paste

Clone an HTML canvas and its content


I have a piece of HTML code with a canvas I'd like to duplicate by the click of a button. I've tried this code so far but I'm a bit clueless about what's missing. If you could include any piece of code it would be really useful to me as I'm a beginner Thank you

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

Solution

  • You can't pass the parameter oldCnv in an onclick action to the function. Besides that, after you return newCanvas the document.body.appendChild(newCanvas) won't get called.

    The following will work. Use this code:

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