Mad Program
Mad Program

Reputation: 139

Dynamic resize of canvas and its contents

i'm a beginner in Javascript so please bear with me.

Basically I'm making a sandbox drawing facility for a website using Javascript. And this is done using the canvas. What I need to do is to be able to resize the canvas dynamically but at the same time keep everything on the canvas to scale.

I don't think this question has been asked before. It seems trivial but I currently have all my objects on the canvas defined in absolute coordinates. I also have mouse events to use to draw things. And when I want to enlarge the canvas (by doubling the size say). All the objects inside won't be enlarged properly to scale and the mouse coordinate system would be messed up too.

Only solution i can think of is add a scale factor to ALL my drawing parts, but this is very tricky with a lot of code. Is there a better way?

Upvotes: 0

Views: 508

Answers (1)

markE
markE

Reputation: 105015

If you don't mind jaggies on your double-sized canvas drawings then you can simply use CSS to double-size your canvas. Then divide every incoming mouseEvent coordinate by 2.

If you don't want jaggies on your double-sized canvas then:

  • Double-size the canvas element: canvas.width*=2 and canvas.height*=2 This automatically erases all canvas content.
  • Scale up the canvas: context.scale(2,2)
  • Redraw all your drawing parts using the unchanged original coordinates. A happy note: you do not have to scale any of your drawing coordinates -- context.scale automatically does that for you.
  • Divide every incoming mouseEvent coordinate by 2.

Upvotes: 2

Related Questions