I was working on a real time whiteboard. I want to create an Infinite canvas, which can be zoomed using the mouse wheel and panned using drag, using javascript.During the zoom and pan the items drawn on the canvas must also be affected. Is there a was to achieve this without using any external library?
Advertisement
Answer
Yes, but it’ll take a bit of work. The general idea of what you’ll do is the following:
- You will need to keep track of the position of the “camera”, as well as how close it is to the content – a zoom factor
- You will need to attach event listeners to different mouse actions to cause the camera’s state to change
- When you drag or zoom, you will need to redraw your canvas with the new positions and sizes of all the content. Some math will have to be done to know what the new canvas content is.
- There may or may not be certain performance issues you have to address if there’s a lot of content on the canvas.
An alternative, possibly quicker approach, but maybe less powerful, would be to not use canvas, and use some CSS magic instead with plain HTML. The basic concept here is that you’ll have a 0x0 div as your plane. That div will contain your content, which may include content such as custom SVGs. Each of its children will break out of the div, and will be positioned relative to it. When you drag, you just move the div (through transform: translate()). When you zoom, you just scale the div (through transform: scale()).
Some useful references if taking the second approach:
- CSS transform – to move and scale the whiteboard
- CSS position – to position content on the whiteboard, and for the general layout
- CSS overflow – to crop the whiteboard