Use image as the fill pattern in JavaScript

Description

The following code shows how to use image as the fill pattern.

Example


<!DOCTYPE HTML>
<html>
<head>
<script>
function drawTriangle(context, x, y, triangleWidth, triangleHeight, fillStyle){
context.beginPath();<!--   ww  w  . ja v  a2s.c  o m-->
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(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var grd;
var triangleWidth = 150;
var triangleHeight = 150;
var triangleY = canvas.height / 2 - triangleWidth / 2;

// pattern fill (right)
var imageObj = new Image();
imageObj.onload = function(){
var pattern = context.createPattern(imageObj, "repeat");
drawTriangle(context, canvas.width  /2, 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>

Click to view the demo

The code above generates the following result.

Use image as the fill pattern in JavaScript
Home »
  Javascript Tutorial »
    Canvas »
      Canvas Draw
Javascript Tutorial Canvas Draw
Change the stroke style in JavaScript
Clip a region in JavaScript
Control line width in JavaScript
Create Radial Gradient on HTML5 canvas in J...
Create a rainbow radial gradient in JavaScr...
Create linear gradient in JavaScript
Draw an image on HTML5 Canvas in JavaScript
Draw transparent shapes on HTML5 Canvas in ...
Get canvas context in JavaScript
Restore a drawing state in JavaScript
Save and restore Canvas states with button ...
Set color to transparency when drawing on c...
Set shadow color and blur in JavaScript
Use image as the fill pattern in JavaScript