HTML canvas createPattern() Method

Introduction

Repeat an image both horizontally and vertically:

View in separate window

<!DOCTYPE html>
<html>
<body>

<p>Image to use:</p>
<img src="image4.png" id="lamp" width="32" height="32">
<p>Canvas:</p>

<button onclick="draw('repeat')">Repeat</button>
<button onclick="draw('repeat-x')">Repeat-x</button>
<button onclick="draw('repeat-y')">Repeat-y</button>
<button onclick="draw('no-repeat')">No-repeat</button>

<canvas id="myCanvas" width="300" height="180" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
function draw(direction) {
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  ctx.clearRect(0, 0, c.width, c.height);
  var img = document.getElementById("lamp")
  var pat = ctx.createPattern(img, direction);
  ctx.rect(0, 0, 150, 100);//from  www  .  j  a  v a 2 s  .  co  m
  ctx.fillStyle = pat;
  ctx.fill();
}
</script>

</body>
</html>

The createPattern() method repeats the specified element in the specified direction.

The element can be an image, video, or another <canvas> element.

The repeated element can be used to draw/fill rectangles, circles, lines etc.

context.createPattern(image, "repeat|repeat-x|repeat-y|no-repeat");

Parameter Values

Parameter Description
image Sets the image, canvas, or video element of the pattern to use
repeatDefault. The pattern repeats both horizontally and vertically
repeat-x The pattern repeats only horizontally
repeat-y The pattern repeats only vertically
no-repeat The pattern will be displayed only once (no repeat)



PreviousNext

Related