I would like to be able to load one single sprite sheet that has many small images, and then be able to assign parts of the big image to several variables (easily done in CSS and browser only loads one image).
Yes there is indeed! The syntax is as follows:
image(img,[sx=0],[sy=0],[sWidth=img.width],[sHeight=img.height],[dx=0],[dy=0],[dWidth],[dHeight])
sx, sy etc are the start position relative to the image, sWidth, sHeight are the width and height of the subset of the image. dx, dy are where you want to draw it on canvas and dWidth, dHeight are how big you want to draw the image.
Thank you so much. That helped me a lot.
For anyone else coming here from google, you can also use Image.get:
// do this in preload
const spritesheet = loadImage('spritesheet.png')
// get portion of spritesheet image
const sprite = spritesheet.get(x, y, width, height)
// show single sprite
image(sprite, x, y, width, height)
EDIT: however, after modifying my app (where I'm doing over 100 image renders per frame), I noticed Image.get is significantly less performant than doing it inline as @limzykenneth showed
@limzykenneth's post gives the parameters you need, but I guess their roles have changed.
image(img,[sx=0],[sy=0],[sWidth=img.width],[sHeight=img.height],[dx=0],[dy=0],[dWidth],[dHeight])
The last parameter pair is funky. . .
Let's say you have a spritesheet of playing cards of 4 rows, 13 items, each card is w100 h100. If you do the following . . .
image(card_spritesheet, 10,10, sWidth=100,sHeight=100, 0,0, 200,200);
| |
2 of Hearts squeeze these pixels into the "frame"
. . . then you will have output the size of one card whose content will be 2 cards wide and 2 cards tall. It will show the 2 & 3 of hearts as well as the 2 & 3 of clubs.
Most helpful comment
Yes there is indeed! The syntax is as follows:
sx, sy etc are the start position relative to the image, sWidth, sHeight are the width and height of the subset of the image. dx, dy are where you want to draw it on canvas and dWidth, dHeight are how big you want to draw the image.