P5.js: Is there a way to load an image from a sprite sheet in p5.js?

Created on 25 Aug 2016  路  4Comments  路  Source: processing/p5.js

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).

Most helpful comment

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.

All 4 comments

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])
  • sx/sy: placement on the output canvas
  • sWidth/sHeight: size on the output canvas, the _"frame"_ of the individual sprite
  • dx/dy: upper-left 0,0 point on the origin image (spritesheet) of what you want to grab
  • dWidth/dHeight: pixel dimensions to grab from the origin image

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.

Was this page helpful?
0 / 5 - 0 ratings