0

I am making a web app where you can draw in a grid (like pixel-art). Say I have a 32x32 grid like this:

enter image description here

I can easily calculate the width and height of each box:

let boxWidth = canvas.width / 32
let boxHeight = canvas.height / 32

I am in the process of implementing a zoom-in and zoom-out feature and I managed to make it work:

let boxWidth = (canvas.width / 32) * scale
let boxHeight = (canvas.height / 32) * scale

// calculate new boxWidth and boxHeight every time the scale changes, and then redraw the whole canvas

If I set the scale to 1.5, for instance, the grid above will look like this:

enter image description here

Works perfectly. However, the "issue" is that it only zooms from the (0, 0) position, not from where the mouse pointer is.

To be quite honest, I have absolutely no idea how I would implement such feature. I am guessing that not only would I have to change each box's width and height, I would have to transform their position as well?

If anyone could clarify and give me hints as to how to proceed, I'd be more than grateful

Thank you

kibe
  • 90
  • 1
  • 8
  • 26
  • 1
    Sure, applying the scaling, then translating to mouseX, mouseY seems reasonable. – ggorlen Dec 22 '20 at 00:22
  • 1
    I'm not exactly sure about your zoom though process, but why `* scale` at all? Once the canvas is resized `ctx.clearRect(0, 0, canvas.width, canvas.height)` then rerun your drawing function without `* scale` since it's based on the canvas anyways. – StackSlave Dec 22 '20 at 00:26
  • might be answered here: https://stackoverflow.com/questions/2916081/zoom-in-on-a-point-using-scale-and-translate – bozdoz Jan 15 '21 at 04:07

0 Answers0