0

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

4
  • Worksforme. The background is static, and the box that shows it is moving over it. Commented Aug 25, 2013 at 12:28
  • @Bergi I don't know how to explain what I really want :) the box is changing the position, but the background is not the same all the time when the box is moving. So it looks like scrolling background. I want it just like drawImage (but i cant use becouse I need something for irregular shapes). Commented Aug 25, 2013 at 12:41
  • So you want to make the fillpattern relatively positioned to the drawn shapes? Commented Aug 25, 2013 at 13:10
  • @Bergi I found this simple example to show what I mean: jsbin.com/oxuyeq/8/edit . The triangle is just like mine box - the background move when you move the shape. And I want to achive the second, rectangle example - background deosnt move when you move it. Of course I want use my example to make it work. Commented Aug 25, 2013 at 13:26

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.