Trying to display image (sprite) on mouseclick

Hi guys, I am new to p5.js and don’t know what I’m doing wrong. I am trying to display a sprite that I have created on a mouseclick. Unfortunately it doesn’t display. This also happens if use a basic image and not an animated sprite. If I just display the sprite or image in the draw function, it displays correctly.

My code looks like this:

let spritedata;
let spritesheet;
let animation = [];

function preload() {
    spritedata = loadJSON("assets/explosion/explosion.json");
    spritesheet = loadImage("assets/explosion/explosion.png")

function setup() {
    createCanvas(windowWidth, windowHeight - 4)

    let frames = spritedata.frames;

    for (let i = 0; i < frames.length; i++) {
        let pos = frames[i].position;
        let img = spritesheet.get(pos.x, pos.y, pos.w, pos.h);


function draw() {

function mouseClicked(event) {

    image(animation[frameCount % animation.length], event.screenX, event.screenY)


and welcome to the forum.

So, mouseClicked eventhandler draws an image as supposed. But then draw() is called and background command covers it. Draw() is called 60 times a second so background() in it covers everything every 1/60th second.

I would move background to setup(). Then you would set background only once at setup. You could also call noLoop() function to prevent draw() function calls.


Thank you so much, this worked fine :slight_smile:

Now the sprite is being displayed on the canvas but is not moving…would you know why?

Well I think it’s because mouseClick() event is called only when you click mouse, so image command is run only then. I don’t know how this command works.

Let’s assume you wanted animation to start with mouse click and stop or pause with another click.
You could then have

animate = False;

function mouseClicked(event) {
    if(animate) {  //animate is True
       animate = False;
       noLoop();  //stops draw() loop
       background('#fff');  //clears the canvas
    } else { //animate is False
       animate = True;
       loop();  // start draw() loop

the in draw() you would have the command to run the animation

I believe you’re mixing up Python & JS syntaxes. :snake:
In JS (Java as well) it’s true & false, not True & False: :coffee:

That’s True (Capital intended). Last two languages I’ve coded with are Java and Python. Javascript is an occasional sidetrack when I want to do art to web.