/

HTML / CSS / JavaScript Tutorial

JavaScript canvas2d object method: createPattern()

[this page | pdf | back links]

The createPattern() method of the JavaScript DOM object returned by the getContext("2d") method applied to the HTML <canvas> element repeats a specific element in a specific direction (the element can be an image, video or another canvas element).

 

It has the following syntax with the following parameters.

 

context.createPattern(image, repeatspecification)

 

Parameter

Required / Optional

Description

image

Required

Element to be used in pattern

repeatspecification

Required

Parameter that specifies how repeating is to be carried out. Can take one of these values:

-        repeat: pattern repeats both horizontally and vertically

-        repeat-x: pattern only repeats horizontally

-        repeat-y: pattern only repeats vertically

-        no-repeat: pattern not repeated

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
Image we will create a pattern from:<br>
<img id="shape" src="Pictures/Shape2smaller.jpg"><br><br>
This image drawn onto a canvas<br>
<span id="element"></span>

<script>
var x2 = document.createElement("CANVAS");
x2.setAttribute("width", "200");
x2.setAttribute("height", "100");
x2.setAttribute("style", "border: 1px solid black");
var c2 = x2.getContext("2d");

c2.clearRect(0,0,x2.width,x2.height);
var img = document.getElementById("shape");
var pat = c2.createPattern(img,"repeat");
c2.rect(30,10,150,80);
c2.fillStyle = pat;
c2.fill();

document.getElementById("element").appendChild(x2);
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodCanvas2dCreatePattern() {
  var x = document.createElement("CANVAS"); var c = x.getContext("2d"); return !!c.createPattern;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile