JSFiddle - React, Tailwind, and code Playground

by Virginie LE GUEN BERTHEAUME

CSS

canvas {
  border: 1px solid black;
}

JavaScript

// By Simon Sarris
// www.simonsarris.com
// [email protected]
//
// Last update December 2011
//
// Free to use and distribute at will
// So long as you are nice to people, etc

// Constructor for Ball objects to hold data for all drawn objects.
// For now they will just be defined as rectangles.
function Ball(image, x, y) {
  this.x = x || 0;
  this.y = y || 0;
  this.img = image;
  this.w = image.width;
  this.h = image.height;
}

// Draws this Ball to a given context
Ball.prototype.draw = function(ctx) {
  ctx.fillStyle = this.fill;
  ctx.drawImage(this.img, this.x, this.y);
}

// Determine if a point is inside the Ball's bounds
Ball.prototype.contains = function(mx, my) {
  // All we have to do is make sure the Mouse X,Y fall in the area between
  // the Ball's X and (X + Width) and its Y and (Y + Height)
  return (this.x <= mx) && (this.x + this.w >= mx) &&
    (this.y <= my) && (this.y + this.h >= my);
}

function CanvasState(canvas) {
  // **** First some setup! ****

  this.canvas = canvas;
  this.width = canvas.width;
  this.height = canvas.height;
  this.ctx = canvas.getContext('2d');
  // This complicates things a little but but fixes mouse co-ordinate problems
  // when there's a border or padding. See getMouse for more detail
  var stylePaddingLeft, stylePaddingTop, styleBorderLeft, styleBorderTop;
  if (document.defaultView && document.defaultView.getComputedStyle) {
    this.stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingLeft'], 10) || 0;
    this.stylePaddingTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingTop'], 10) || 0;
    this.styleBorderLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10) || 0;
    this.styleBorderTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10) || 0;
  }
  // Some pages have fixed-position bars (like the stumbleupon bar) at the top or left of the page
  // They will mess up mouse...