1

I'm trying to zoom in or out my canvas drawing, but if I only scale the context nothing happens.

Do I need to re-draw it after the scale? Is there any method to scale directly the context without drawing it every time I try to zoom in or out?

PS: I want to zoom in and out with an HTML5 <input type="range"> controlled by a script, and that's already working.

dMar
  • 55
  • 7
  • Yes, you have to redraw it every time. There's no way of getting around this. This is actually a good thing because it allows you to perform lots of transforms on the canvas without redrawing every time. If it did, high-intensity games and animations wouldn't be possible. – Mike Cluck Oct 04 '16 at 17:45
  • no, you certainly don't have to redraw it everytime. leave the width and height attributes alone and use css to scale/"zoom" the entire thing. – Robert Parham Oct 04 '16 at 17:52
  • Like this: https://jsfiddle.net/43ejq0op/ – Robert Parham Oct 04 '16 at 17:58

2 Answers2

1

Like Mike said, the best solution is to redraw it. Zooming in with css is a solution, but there's a big loss in quality.

dMar
  • 55
  • 7
0

I'm copying my answer from another question I already answered today..

Canvas is like an image. It has it's own physical dimensions but can still be scaled with CSS. Use the width and height attributes to set the physical dimensions and then use CSS to scale it with a % to make it responsive zoom it.

Example...

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.rect(20, 20, 150, 100);
ctx.stroke();
<canvas id="myCanvas" width="300" height="150" style="width:100%;"></canvas>

Here is an overly simplified example: https://jsfiddle.net/43ejq0op/

Community
  • 1
  • 1
Robert Parham
  • 704
  • 3
  • 10
  • 1
    This does work but, as you can see in your example, leads to ugly pixelization. If that doesn't matter then it's a great solution. Otherwise, OP will have to re-draw the whole scene (or at least the subset that has been scaled) – Mike Cluck Oct 04 '16 at 18:56