Home > Web Front-end > H5 Tutorial > body text

Detailed explanation of HTML5 canvas tiling code

黄舟
Release: 2017-04-18 09:59:11
Original
2750 people have browsed it

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);
}
Copy after login

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();
}
Copy after login

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 elements.
Repeated elements can be used to draw/fill rectangles, circles or lines, etc.

JavaScript Syntax:

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

Parameters Description

#repeatDefault. Specifies the image, canvas, or video element to use. repeat-xThe pattern repeats horizontally only. repeat-yThe pattern repeats only in the vertical direction. no-repeatThis 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template