Skip to content

Instantly share code, notes, and snippets.

@dalelane
Last active July 21, 2019 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dalelane/002138f1cfeb6f654f68622ece8f5f88 to your computer and use it in GitHub Desktop.
Save dalelane/002138f1cfeb6f654f68622ece8f5f88 to your computer and use it in GitHub Desktop.
Converting from Scratch's coordinates to the HTML canvas
// assumptions about the Scratch coordinate system
var SCRATCH_CANVAS_TOP = 180;
var SCRATCH_CANVAS_LEFT = -240;
var SCRATCH_CANVAS_RIGHT = 240;
var SCRATCH_CANVAS_WIDTH = SCRATCH_CANVAS_RIGHT - SCRATCH_CANVAS_LEFT;
// where is the top-left corner of the sprite we're interested in?
var costume = targetSprite.getCurrentCostume();
var scratchX = targetSprite.x - costume.rotationCenterX;
var scratchY = targetSprite.y + costume.rotationCenterY;
// how big is the sprite we're interested in?
var sizeRatio = targetSprite.size / 100;
var scratchWidth = costume.size[0] * sizeRatio;
var scratchHeight = costume.size[1] * sizeRatio;
// the size of the HTML canvas will vary depending on whether
// the project is in full-screen mode or not, so we need
// to know the scale factor to use
// (assume that it'll be the same for both width and height, so
// we just pick one)
var scaleFactor = htmlCanvas.width / SCRATCH_CANVAS_WIDTH;
// where is the top-left corner of the sprite on the HTML canvas?
var htmlX = scaleFactor * ( scratchX + SCRATCH_CANVAS_RIGHT );
var htmlY = -scaleFactor * ( scratchY - SCRATCH_CANVAS_TOP );
// how big is the sprite on the HTML canvas?
var htmlWidth = scaleFactor * scratchWidth;
var htmlHeight = scaleFactor * scratchHeight;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment