JarsOfJam-Scheduler
JarsOfJam-Scheduler

Reputation: 3149

HTML5 Canvas: Absolute scaling its contents

I would want to rescale the content of the canvas, so in a loop, I use the rescale function. However, as I could have expected, it works as in this example: 1 -> 2 -> 4 -> 8 (with a factor = 2). What I would want to have is...: 1 -> 3 -> 5 -> 7 (with a factor = 2). So I should not use scale, but what function?

Note that I don't want, and can't, use CSS, or other stuff than the canvas' JS API by default. However if there is no solution, tell me yours even if it relies on CSS...

Upvotes: 0

Views: 279

Answers (1)

Blindman67
Blindman67

Reputation: 54026

Absolute scale

You can set an absolute scale by replacing the current transform with ctx.setTransform

All the other transformation functions ctx.scale, ctx.translate, ctx.rotate, ctx.transform apply the transform to the existing transform. That is why your scale doubles each time (2,4,8,16)

Thus to set an absolute scale

scale = 1;
ctx.setTransform(scale, 0, 0, scale, 0, 0);

To scale by 3

scale += 2;
ctx.setTransform(scale, 0, 0, scale, 0, 0);

To scale by 5 add 2 again

scale += 2;
ctx.setTransform(scale, 0, 0, scale, 0, 0);

Note this replaces any existing transformations.

To set a complete uniform transform

function setTransform(ctx, x, y, scale, rotate) {
    ctx.setTransform(
         Math.cos(rotate) * scale, Math.sin(rotate) * scale,  // x axis
        -Math.sin(rotate) * scale, Math.cos(rotate) * scale,  // y axis is 90deg CW from x axis
        x, y  // translation as absolute sets origin in px from top left of canvas
    );
}

Upvotes: 1

Related Questions