javascriptandroidiostouchtouchstart

How to make this javascript "fireworks on click" code to also work on touch screens?


I wanted to make a simple temporary "Happy 2017" page on my site, and I've found on Code.pen a JS code for fireworks that looked pretty interesting:

https://codepen.io/chuongdang/pen/yzpDG

The code works wonderfully with a mouse, as the firework explodes exactly where you clicked, but it doesn't work at all with touch commands, making it not interactive at all on touch screens. I can see that the code calls mousedown, mousemove and mouseup events, but not touchstart and touchend:

 if( timerTick >= timerTotal ) {
    if( !mousedown ) {
        fireworks.push( new Firework( cw / 2, ch, random( 0, cw ), random( 0, ch / 2 ) ) );
        timerTick = 0;
    }
} else {
    timerTick++;
}

if( limiterTick >= limiterTotal ) {
    if( mousedown ) {
        fireworks.push( new Firework( cw / 2, ch, mx, my ) );
        limiterTick = 0;
    }
} else {
    limiterTick++;
}

I guess that's the problem, but being a complete JS noob I lack the knowledge to make it recognize touch coordinates. Is there a simple way to do so?


Solution

  • This is a suggestion, it may work or not.

    Try and associate it to a different event.

    At the link you sent (https://codepen.io/chuongdang/pen/yzpDG), there are two event listeners to handle both onmousedown and onmouseup events.

    canvas.addEventListener( 'mousedown', function( e ) {
        e.preventDefault();
        mousedown = true;
    });
    
    canvas.addEventListener( 'mouseup', function( e ) {
        e.preventDefault();
        mousedown = false;
    });
    

    Try and replace them by the following code:

    canvas.addEventListener( 'click', function( e ) {
        e.preventDefault();
        mousedown = true;
      setTimeout(function() {
        mousedown = false;
      }, 20);
    });
    

    mousedown is just the variable it uses to check if a click is being made. As long as it is true, it will set the target to the fireworks.

    So, what the code above does is to associate the whole thing with a different event click (which is sometimes interchangable with a screen tap). When a click is made, it sets mousedown as true, count 20 milisecounds, and them sets mousedown as false again.

    I hope this helped! =)