I am working on a website project recently, and I use a lot of canvas. There is a need for drawImage to draw the picture in the canvas. The picture is relatively small, so I need Tile effect as background image. PS (the height and width of the background image are 10px, and the height and width of the canvas to be drawn are 200px)
Since it was drawn from drawImage at the beginning, the method one
var canvas = document.getElementById("canvasId"); var ctx = canvas.getContext("2d"); var img = new Image(); //需要平铺的图片 img.src = "test1_bg.jpg"; img.onload = function (){ var can = document.createElement("canvas"); can.width = 10; can.height = 10; var ctx2 = can.getContext("2d"); ctx2.drawImage(img,0,0,10,10,0,0,10,10); ctx.fillStyle = ctx.createPattern(can,"repeat"); ctx.fillRect(0,0,200,200); }
was used The height and width of the background image are 10, which is a bit cumbersome. Why not do it in one step? So it was changed to this way
var canvas = document.getElementById("canvasId"); var ctx = canvas.getContext("2d"); var img = new Image(); //需要平铺的图片 img.src = "test1_bg.jpg"; img.onload = function (){ var pat = ctx.createPattern(img,"repeat"); ctx.rect(0,0,200,200); ctx.fillStyle = pat; ctx.fill(); }
GOOD!
Let’s reiterate the definition of createPattern
The createPattern() method repeats the specified element in the specified direction.
Elements can be images, videos, or other
JavaScript Syntax:
context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");
Parameters Description
Default. Specifies the image, canvas, or video element to use. | |
The pattern repeats horizontally only. | |
The pattern repeats only in the vertical direction. | |
This pattern is only displayed once (not repeated). |
The above is the detailed content of Detailed explanation of HTML5 canvas tiling code. For more information, please follow other related articles on the PHP Chinese website!