HTML5 Game - Copying and pasting sections of the canvas

Introduction

We can use drawImage() method to copy sections of the canvas.

First, we'll draw a shape in the center of the canvas.

We'll copy the right side of the canvas and then paste it to the left, and then we'll copy the left side of the shape and then paste it to the right.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML> 
<html>
    <head>
        <script>
            function drawSpade(context, x, y, width, height){
                context.save();/* w  w  w  .ja  v  a  2s  .com*/
                
                context.beginPath();
                context.moveTo(x, y);
                
                // top left of spade          
                context.rect(x,y,width,height);
                context.closePath();
                context.fillStyle = "black";
                context.fill();
                context.restore();
            }        
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
             // draw spade 
             let spadeX = canvas.width / 2; 
             let spadeY = 20; 
             let spadeWidth = 140; 
             let spadeHeight = 200; 
              
             // draw spade in center of canvas 
             drawSpade(context, spadeX, spadeY, spadeWidth, spadeHeight); 

             context.drawImage( 
             canvas,          
             spadeX,         // source x 
             spadeY,         // source y 
             spadeWidth / 2,     // source width 
            spadeHeight,       // source height 
            spadeX - spadeWidth,  // dest x 
            spadeY,         // dest y 
            spadeWidth / 2,     // dest width 
            spadeHeight        // dest height 
          ); 

            context.drawImage( 
            canvas,  
            spadeX - spadeWidth / 2,  // source x    
            spadeY,           // source y 
            spadeWidth / 2,       // source width 
            spadeHeight,         // source height 
            spadeX + spadeWidth / 2,   // dest x 
            spadeY,           // dest y 
            spadeWidth / 2,       // dest width 
            spadeHeight          // dest height 
          ); 
         }; 


        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

To copy a section of the canvas, we can pass the canvas object to the drawImage() method instead of an image object:

Context.drawImage(canvas,
                  sourceX,
                  sourceY,
                  sourceWidth, 
                  sourceHight, 
                  sourceHeight,
                  sourceHeight, 
                  destX, 
                  destY, 
                  destWidth, 
                  destHeight); 

Related Topic