Today lets learn how to create patterns on canvas using image.
index.html and myStyle.css files are kept same as illustrated in previous video tutorial: Canvas State: HTML5
Related Topics:
Canvas Basics: HTML5
Draw Rectangle: HTML5 Canvas
Javascript file
myScript.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | window.onload = canvas; function canvas() { var myCanvas = document.getElementById("myCanvas"); if( myCanvas && myCanvas.getContext("2d") ) { var context = myCanvas.getContext("2d"); var myImg = new Image(); myImg.src = "technotip.png"; myImg.onload = function() { context.fillStyle = context.createPattern(myImg, "no-repeat"); context.fillRect(0, 0, context.canvas.width, context.canvas.height); } } } |
Here we create a new image object myImg and set it’s source to a image technotip.png Once the object loads the source image we call an anonymous function. Here we set fillStyle property with the pattern we create out of the image. createPattern takes 2 parameter, first on being the pattern itself and the second one being the image repeat value, it takes repeat, no-repeat, repeat-x or repeat-y as it’s value.
Canvas Image Patterns: HTML5
[youtube https://www.youtube.com/watch?v=AhxDlK5dOHY]
Note:
We can create pattern out of another canvas element or an image or even a video file.