user1892613
user1892613

Reputation:

Repeating a method to draw a pattern on 2D Canvas

I have a method which draws an image using the context.fillRect() method. I want this image to be drawn repeatedly i.e in a tiled format along the x and y axes as it is small in size (15 pixels in length).

It is to fill my canvas of 700 px width, 500 px height.

Can this be done using the context.createPattern() method? How?

Upvotes: 0

Views: 1183

Answers (2)

JoshuaOne
JoshuaOne

Reputation: 1

Based on your response to apsillers answer, I would recommend you draw your desired pattern to another canvas element. You can then pass the completed drawing to ctx.createPattern.

var drawing = document.createElement('canvas');

//Do necessary drawing
//ctx.fillRect(etc)

var ptrn = ctx.createPattern(drawing,'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0,0, canvas.width,canvas.height);

HTML5 Canvas - Repeat Canvas Element as a Pattern

Upvotes: 0

apsillers
apsillers

Reputation: 115950

The secret sauce to using context.createPattern is the context.fillStyle property.

First, you create the pattern, then you assign the pattern to context.fillStyle, and finally, you use context.fillRect to draw the pattern:

// assuming img is loaded...
var ptrn = ctx.createPattern(img,'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0,0, canvas.width,canvas.height);

There is a complete example on MDN.

Upvotes: 2

Related Questions