BattlefyBlogHistoryOpen menu
Close menuHistory

Canvas is a superposition of 3 spaces

Ronald ChenSeptember 12th 2022

CSS space

When working with CSS, we are often working with the px unit, which stands for pixel. Historically, CSS pixel was the same as display monitor screen pixel, but Apple changed all that when they released Retina displays.

In order to not suddenly have all websites but half the size, Safari pretended to be a a lower resolution screen, but actually render text at full native screen resolution. See window.devicePixelRatio

Suddenly, we are working in two different spaces. CSS px space and screen space.

Screen space

The term screen space comes from computer graphics and for full screen applications, screen space is the same as the native resolution of the display. Typically, the top left is the origin, zero indexed.

But for windowed applications, screen space is a portion of the screen. We however define the origin to be the top left of the window.

In the browser we further define the viewport as the screen space.

For example, if we have a browser window open on a 1080p display, we would have the following.

Canvas and the last space

Canvas is a HTML element, thus exists in CSS space. But it also has its own coordinate system. We can use the ResizeObserver to resize the canvas to ensure it matches the screen space.

But for more complicated canvas diagrams, it is annoying to have to work in screen space.

Imagine we wanted to draw a circle centred at 0,0 with a diameter of 100 units. We also want this circle be displayed as large as possible. I.E. we want to zoom fit to the circle.

At first this seems impossible if our screen space is a 1080p display. What does it even mean for the circle to have a diameter of 100 units and it fills the screen? How can a circle have a diameter of 1080 pixels and a diameter of 100 units. And how does this all change when screen space is an even larger display?

Why do I keep writing units and not pixels? That's because units isn't found in screen space, we can define arbitrary units in world space.

World space is a coordinate system that is independent of screen space. We can define shapes in world space and then decide how we want to display them in screen space.

Here is a demo with app 3 spaces in one picture. Included is an HTML button in the middle to prove we can go from CSS space to screen space to world space to screen space and back to CSS space.

Play around with the code sample and notice how the units change as one resizes the window.

Do you want to learn how to easily flow between spaces? You're in luck, Battlefy is hiring.

Don't break the Internet
September 19th 2022


Powered by