

Here the red zero is the new origin and if you wanted to draw back to the upper left corner of the canvas, you’d need to draw at -20, -20.


That means that as far as the canvas itself is concerned, the coordinate system now looks like this: So if we translate the canvas 20 pixels in the x direction and 20 pixels in the y direction, the new origin starts 20 pixels down and 20 pixels over from the original origin. The red lines and red zero mark the new origin of the canvas, meaning the red lines are the new X and Y zero, with the red zero being 0,0. The lowercase x and y represent a translate distance in the x and y direction. The origin of the canvas starts out in the upper left corner, making it 0,0 in canvas space by default, as shown in the graph above. Calling translate on a canvas moves the canvas and it’s origin to a new point on a grid ( MDN). We’ll start with the simple part, translating. Transformed: x: 0, y: 0 Translating the Canvas The upper left corner of the image will always be the origin 0,0. Clicking and dragging in the canvas will move the image around, and scrolling your mouse wheel while over the canvas will zoom in to and out of the image at the exact position of your cursor. You can also see a fully working JSFiddle here.Ĭheck out the example below. If you just want a fast answer to “how do I transform a point to the transformed canvas space”, click here to go right to the secret sauce. This article goes into why and how this works, but you don’t really need to know that to accomplish this. So, I set out to create a nice modern version that worked and that I could understand, and that made use of the canvas’s built in transformation tracking. And all the examples required you to track your own version of the transformations applied to the canvas, but now with getTransform we can make use of the fact that the canvas already stores all of it’s transforms. All examples and info online followed bad practices or use outdated features to work. I wanted to be able to add intuitive zooming and panning in an image editing web app I was working on, but this turned out to be a bit harder than I expected.
