The Scratch coordinate system

In Scratch 3, the stage in the top right where your sprites live is implemented as an HTML canvas. Unfortunately the internal coordinate system used by Scratch logically to maintain state, and the coordinate system used by HTML canvases both work very differently.

For some of the Scratch blocks I’ve written for Machine Learning for Kids, I need to be able to convert between coordinates and sizes between the two different coordinate systems.

For example, my ML blocks can let a student use an image classifier they’ve trained to recognise what is on the background behind a certain Sprite in their project. To do that, the backdrop image block needs to:

  1. get the location of the Sprite (which will be returned using the Scratch coordinate system)
  2. get the image data of what is rendered on the canvas at that location (using HTML canvas APIs – using the HTML coordinate system)

I couldn’t find a way to convert between the two documented anywhere, and it was a tiny bit fiddly, so I’m documenting it here for the next time I need it!

Scratch’s coordinate system goes from
x=-240 (far left) to x=+240 (far right).
And y=-180 (bottom) to y=+180 (top).

The 0,0 coordinate is in the middle.
x increases from left to right.
y increases from bottom to top.

HTML canvas’ coordinate system goes from
x=0 (far left) to x=+960 (far right)
And y=+720 (bottom) to y=0 (top).

The 0,0 coordinate is in the top left.
x increases from left to right.
y decreases from bottom to top.

The added complication is that students can run their projects in full-screen mode, so the size of the canvas is different, but the top-left is still 0,0 and the y value still decreases as you move down.

The logic to convert that I’ve got in my blocks looks like this:

Tags: ,

Comments are closed.