Zhirayr
Zhirayr

Reputation: 423

Canvas rectangle background image

I want to set background image to my rectangle in the canvas. So far i've done this.

var img = new Image()
    img.src = //Source of an image.
var newPattern = ctx.createPattern(img, "no-repeat");
ctx.fillStyle = newPattern;

And it works, but the problem is, that it applies the image to the canvas, not to the rectangle.

And whenever I change the position of the rectangle, the image remains in the same position.

Can anybody suggest how to fix this, so the image'd be attached to the rectangle.

Upvotes: 0

Views: 5687

Answers (1)

David Hartley
David Hartley

Reputation: 100

If you want to only draw the image within a specified rectangle you can do something like this.

context.rect(x, y, width, height);
context.clip();
context.drawImage(img, 0, 0);

This creates a rectangle at (x, y) with size (width, height) which is used for all future calls to the context. If you want to stop the clipping you will need to add a

context.save();

before the code above and then a

context.restore();

after you have drawn the image.

JSFiddle

Edit: updated to rect

Upvotes: 1

Related Questions