Canvas Pattern
How to Create Pattern
To create pattern, follow these steps
- canvas - Assigning the canvas element to a variable.
- ctx - Assigning the 2d rendering context to another variable by calling the
getContext('2d')
method. - img - Assigning a blank DOM object for a HTML img element by using the Image class to a variable.
- src - Setting the src attribute to the path of a valid image file, you load that image into the image object just as if you set the src attribute of an actual HTML img element.
- ptrn - Assigning a pattern with specified image and repetition using
createPattern()
canvas method to a variable. - fillStyle - Use
fillStyle
canvas property to specify the pattern to use inside shapes (any shape). - fillRect() - Use
fillRect()
canvas method to draws a rectangle that is filled according to the currentfillStyle
.
Example
HTML Online Editor
<!DOCTYPE html>
<html lang="en-US">
<body>
<canvas id="point" width="200" height="200">
Your browser does not support the canvas element.
</canvas>
<script>
window.onload = function() {
var canvas = document.getElementById("point");
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = 'apple.png';
img.onload = function() {
var ptrn = ctx.createPattern(img,'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0, 0, 200, 200);
}
};
</script>
</body>
</html>
Syntax
ctx.createPattern(image, repetition)
Attributes Value
Value | Explanation |
---|---|
image | Specifies an image to be used as the pattern. |
repetition | Specifies how to repeat the pattern's image.
|
Reminder
Hi Developers, we almost covered 93% of Canvas Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in Canvas.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.