requestAnimationFrame test

Demonstrating how the speed increases with every click and older animations stop.

by Chris

HTML

<!--<p>Click within the canvas to test animation</p>-->
   <canvas id="canvas" width=500 height=300></canvas>

CSS

canvas {
  border: dotted 10px #f00;
}

JavaScript

var img = new Image();
img.src = 'https://imgur.com/u2hjhwq.png';
img.onload = function() {
  // init();
};

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

var scale = 1.5;
var width = 100; // Bigger numbers push left <-, smaller right ->
var height = 100;
var scaledWidth = scale * width;
var scaledHeight = scale * height;

var x_click;
var y_click;


function drawFrame(frameX, frameY, canvasX, canvasY) {
  ctx.drawImage(img,
                frameX * width, frameY * height,
                width, height,
                x_click, y_click,
                scaledWidth, scaledHeight);
}

// Number of frames in animation
var cycleLoop = [3, 2, 1, 0, 7, 6, 5];
// Position of sprite in sheet
var currentLoopIndex = 0;
var frameCount = 0;

function step() {

  frameCount++;
  if (frameCount < 30) {
    window.requestAnimationFrame(step);
    return;
  }
  frameCount = 0;
  // ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawFrame(cycleLoop[currentLoopIndex++], 0, 0, 0);
  // Starts animation over
  if (currentLoopIndex >= cycleLoop.length) {
    // If you want to loop back in oposite direction after full animation
    cycleLoop.reverse();
    // Reseting position of which sprite to use
    currentLoopIndex = 0;
  }
  window.requestAnimationFrame(step);
}

function init() {
  // window.requestAnimationFrame(step);
}


canvas.addEventListener("mousedown", getPosition, false);
function getPosition(event) {
   x_click = event.x;
   y_click = event.y;

   x_click -= canvas.offsetLeft * 10;
   y_click -= canvas.offsetTop * 10;
   step();
   // testClick();
   // window.requestAnimationFrame(step);
}
function testClick() {
   console.log("x: " + x_click + " y: " + y_click);
}