Amay
Amay

Reputation: 1521

JavaScript Canvas createPattern

I have problem with canvas createPattern. I have two boxes, both will move after pressing a keyarrow:

Example: http://jsfiddle.net/wA73R/1/

The problem is that the box background filled by createPattern also is moving. How to avoid that? Is there any solution? The big box is only an example (drawImage is not the good solution for me, I need something that will repeat background image).

Thank you for help

Upvotes: 0

Views: 960

Answers (1)

Bergi
Bergi

Reputation: 665286

The problem is that the box background filled by createPattern also is moving.

Actually your problem is that the background is not moving - it is static, while you are drawing your rectangle to different positions.

How to avoid that?

The pattern will always be drawn at the coordinate origin, whose actual position is defined by the current transformation. In future you will be able to transform the pattern itself with the setTransform method, but since that currently is not implemented anywhere you instead will have to change the global transformation matrix.

In your case it means, that instead of drawing your rectangle at x/y, you translate the whole context to x/y and draw your rectangle at 0/0 then:

ctx.fillStyle=pattern;
ctx.save();
ctx.translate(boxes[i].x - left , boxes[i].y);
ctx.fillRect(0, 0, boxes[i].width, boxes[i].height);
ctx.restore();

(updated demo)

Upvotes: 2

Related Questions