HTML5 Game - Canvas Pattern

Introduction

We can use pattern as fill style.

To create a pattern object, use the createPattern() method.

It requires an image object and a repeat option:

let pattern=context.createPattern(imageObj, repeatOption); 

The repeatOption can take one of the four options:

  • repeat
  • repeat-x
  • repeat-y
  • no-repeat.

The repeatOption is defaulted to repeat.

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
         function drawTriangle(context, x, y, triangleWidth, triangleHeight, fillStyle){ 
             context.beginPath(); /*from www  .  j a  v a  2  s  .  c  om*/
             context.moveTo(x, y); 
             context.lineTo(x + triangleWidth / 2, y + triangleHeight); 
             context.lineTo(x - triangleWidth / 2, y + triangleHeight); 
             context.closePath(); 
             context.fillStyle = fillStyle; 
             context.fill(); 
         } 

            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
                
              
             let grd; 
             let triangleWidth = 150; 
             let triangleHeight = 150; 
             let triangleY = canvas.height / 2 - triangleWidth / 2; 

        // pattern fill (right) 
        let imageObj = new Image(); 
        imageObj.onload = function(){ 
            let pattern = context.createPattern(imageObj, "repeat"); 
            drawTriangle(context, canvas.width * 4 / 5, triangleY, triangleWidth, triangleHeight, pattern); 
        }; 
        imageObj.src = "http://java2s.com/style/download.png"; 
    };   


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

Related Topics