Mikeb
Mikeb

Reputation: 791

Scaling Images in HTML5 canvas

I have a number of objects that represent an image that I want to draw onto a canvas. Each object has a X, Y, Scale property as well as a render method that gets passed a canvas object. then the canvas tag is passed to each object's render method and they all need to render themselves to the canvas.

The problem I have is that scaling is being done from the origin of the canvas and not the origin of the image. To fix this I've tried the following:

canvas.translate(-this.X, -this.Y);
canvas.scale(this.Scale, this.Scale);
canvas.translate(this.X, this.Y);

The problem with the above code is that it looks like you can only have 1 translation and the 3rd line which is supposed to move the object back to its original position becomes the translation when calling drawImage. If I remove the 3rd line I get the correct scaling origin but the image is moved to 0,0 and not rendered in the correct location.

What is the proper way to do this type of scaling?

Upvotes: 2

Views: 1975

Answers (1)

Prusse
Prusse

Reputation: 4315

Try:

canvas.translate(this.X, this.Y);
canvas.scale(this.Scale, this.Scale);
canvas.translate(-this.X, -this.Y);

But keep in mind, doing this you will need to do alot of ctxt.save();s and ctxt.restore();s if you got the width and height of the imagens you could simple do ctxt.drawImage(this.image, this.X, this.Y, this.Width*this.Scale, this.Height*this.Scale); since you don't need to mess with the context state stack it may be faster.

Edit:

The transformations don't affect the origin. What happen is that they must be applied in reverse order. Remember this methods are just shortcuts for stacking matrices in the transformation stack.

Upvotes: 3

Related Questions