How To Display, Tile, Clip Image In Html5 Canvas Examples

This article shows you an example of how to display, tile, and clip images in Html5 canvas.

1. How To Display, Tile, Clip Image In Html5 Canvas.

1.1 How To Display Image In Html5 Canvas.

  1. Create an instance of the Image object.
    img = new Image();
  2. Assign the image path and name to the image object’s src attribute.
    img.src = '/usr/....../test.png'
  3. Assign a function to the image object’s onload event, and draw the image in the function when the image is loaded completely.
    img.onload = function(){
    
        ctx.drawImage(img, 10, 10);
        
    }
  4. Call the canvas context object’s drawImage() function to draw the image on the canvas.
  5. The drawImage() function provides 3 version with different parameters.
  6. drawImage(image_object, x, y) will draw the image with the image top-left point located at the point (x, y), the image size is original.
  7. drawImage(image_object, x, y, width, height) is similar to the above method and changes the image size to width and height.
  8. drawImage(image_object, sx, sy, sw, sh, dx, dy, dw, dh) will copy the original image from point (sx,sy) with the size (sw,sh) to the destination, the destination top-left point coordinate is (dx, dy) and the destination image width will be changed to (dw, dh).

1.2 How To Tile Image In Html5 Canvas.

  1. Call the canvas context object’s createPattern(image, type) method to create a pattern variable.
  2. The image parameter is an Image object, the type parameter’s value can be no-repeat, repeat-x, repeat-y, repeat.
    var pattern = ctx.createPattern(img, 'repeat');
  3. no-repeat: do not tile the image, repeat-x: tile the image in the horizontal direction, repeat-y: tile the image in the vertical direction, repeat: tile the image in both directions.
  4. Then you can assign the above pattern variable to the context object’s fillStyle property.
    ctx.fillStyle = pattern
  5. Then you can draw a shape, and you can see the image is tiled in the shape.
    ctx.fillRect(10, 10, 300, 300);

1.3 How To Clip Image In Html5 Canvas.

  1. Draw a shape on canvas for example draw a rectangle with borders only.
    ctx.rect(100, 100, 190, 90);
    ctx.stroke();
  2. Call the context object’s clip() function to define the above shape area as the clipped area on the image.
    ctx.clip();
  3. Then you can call the canvas context’s drawImage() function to draw the image, and you can find it will only draw the image part that is displayed in the above shape area scope on canvas.
    ctx.drawImage(img, 10, 10);

2. Display, Tile, Clip Image In Html5 Canvas Examples.

  1. The demo video URL is https://youtu.be/t2poBVjHZ30.
  2. First, you should select an image by clicking the Choose File button.
  3. When you click the Display Image button, it will display the image on the canvas using the 3 drawImage() function.
  4. When you click the Tile Image button, it will tile the selected image in a rectangle and circle on the canvas.
  5. When you click the Clip Image button, it will clip the selected image and show the image part in a triangle.
  6. This example contains 2 source files, html5-canvas-display-tile-clip-image.html, html5-canvas-display-tile-clip-image.js.
  7. html5-canvas-display-tile-clip-image.html.
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>How To Display, Tile, Clip Image In Html5 Canvas Examples</title>
    <script type="text/javascript" src="html5-canvas-display-tile-clip-image.js" charset="utf-8"></script>
    <style>
    canvas{
      display:block;
      margin-top:10px;
    }
    </style>
    </head>
    <body>
    <h3>How To Display, Tile, Clip Image In Html5 Canvas Examples.</h3>
    <div>
        <label>Select Image File:</label>
        <input type="file" id="selectedFile" accept="image/*" style="display:block;margin-top: 10px;"/>
        <div style="display:block;margin-top: 10px;">
            <input type="button" value="Display Image" onclick="displayImage('canvas1', 'selectedFile')" />
            <input type="button" value="Tile Image" onclick="tileImage('canvas1', 'selectedFile')" />
            <input type="button" value="Clip Image" onclick="clipImage('canvas1', 'selectedFile')" />
        </div>
        <canvas id="canvas1"></canvas>
    </div>
    </body>
    </html>
  8. html5-canvas-display-tile-clip-image.js.
    var canvasWidth = 1000;
    var canvasHeight = 800;
    
    var imgFolderPath = '/Users/songzhao/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/img/';
    
    function displayImage(canvasId, fileUploderId){
    
        // Get the html canvas object.
        var canvas = document.getElementById(canvasId);
        
        if(canvas==null){
            alert("Can not find the html canvas element with element id " + canvasId);
            return false;
        }
    
        var fileUploader = document.getElementById(fileUploderId);
        if(fileUploader==null){
            alert("Can not find the html file upload element with element id " + fileUploderId);
            return false;
        }
    
    
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;
        canvas.style.display = 'block';
    
        ctx = canvas.getContext('2d');
    
        ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    
        fileName = fileUploader.value;
        
        startIndex = fileName.lastIndexOf('\\');
    
        fileName = fileName.substring(startIndex + 1);
    
        img = new Image();
    
        img.src = imgFolderPath + fileName;
    
        img.onload = function(){
    
            ctx.fillStyle = 'blue';
            ctx.font = "36px Arial";
    
            ctx.drawImage(img, 10, 10);
            ctx.fillText("original image size", 80, 500);
    
            ctx.drawImage(img, 600, 10, 300, 300);
            ctx.fillText("set image size : 300*300", 600, 200);
        
            ctx.drawImage(img, 10, 10, 300, 300, 600, 366, 600, 600);
            ctx.fillText("enlarge original 300*300 to 600*600", 366, 600);
            ctx.fillText("start point is (10, 10) in original", 366, 660);
    
    
        }
    }
    
    
    function tileImage(canvasId, fileUploderId){
    
        // Get the html canvas object.
        var canvas = document.getElementById(canvasId);
        
        if(canvas==null){
            alert("Can not find the html canvas element with element id " + canvasId);
            return false;
        }
    
        var fileUploader = document.getElementById(fileUploderId);
        if(fileUploader==null){
            alert("Can not find the html file upload element with element id " + fileUploderId);
            return false;
        }
    
    
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;
        canvas.style.display = 'block';
    
        ctx = canvas.getContext('2d');
    
        ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    
        fileName = fileUploader.value;
        
        startIndex = fileName.lastIndexOf('\\');
    
        fileName = fileName.substring(startIndex + 1);
    
        img = new Image();
    
        img.src = imgFolderPath + fileName;
    
        img.onload = function(){
    
            var pattern = ctx.createPattern(img, 'repeat');
    
            ctx.fillStyle = pattern;
            
            ctx.fillRect(10, 10, 300, 300);
    
            ctx.beginPath();
    
            ctx.arc(600, 400, 300, 0, 360, false);
    
            ctx.closePath();
    
            ctx.fill();
    
        }
    }
    
    
    
    function clipImage(canvasId, fileUploderId){
    
        // Get the html canvas object.
        var canvas = document.getElementById(canvasId);
        
        if(canvas==null){
            alert("Can not find the html canvas element with element id " + canvasId);
            return false;
        }
    
        var fileUploader = document.getElementById(fileUploderId);
        if(fileUploader==null){
            alert("Can not find the html file upload element with element id " + fileUploderId);
            return false;
        }
    
    
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;
        canvas.style.display = 'block';
    
        ctx = canvas.getContext('2d');
    
        ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    
        fileName = fileUploader.value;
        
        startIndex = fileName.lastIndexOf('\\');
    
        fileName = fileName.substring(startIndex + 1);
    
        img = new Image();
    
        img.src = imgFolderPath + fileName;
    
        img.onload = function(){
    
            // Create a shape to define the clip area scope.
            // In this example, it is a red triangle.
            ctx.fillStyle = 'red';
            ctx.lineWidth = 10;
            ctx.beginPath();
            ctx.moveTo(10, 10);
            ctx.lineTo(400, 10);
            ctx.lineTo(200, 600);
            ctx.lineTo(10, 10);
            ctx.closePath();
            ctx.fill();
            
            // Call the ctx.clip() function to clip the display area.
            ctx.clip();
    
            // When you draw the image again, it will only show the clipped area (which is defined above) of the original image.
            ctx.drawImage(img, 10, 10);
    
        }
    }

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.