JSFiddle - React, Tailwind, and code Playground

by Ajay Patel

HTML

<canvas style="border:1px solid grey;position:absolute;" width='1000' height='1000' id="canvas_back">Your browser does not support canvas</canvas>
<canvas style="border:1px solid grey;position:absolute;" width='1000' height='1000' id='canvas'>Your browser does not support canvas</canvas>
<div style="margin-top:500px;position:absolute;" id="log"></div>
<img style="display:none;" id="img" alt=""...

JavaScript

var canvas = document.getElementById('canvas');
var canvas_back = document.getElementById('canvas_back');
var img = document.getElementById('img');
canvas_back.getContext('2d').drawImage(img, 0, 0);
var W = 1000;
var H = 1000;


if (canvas.getContext) {
    // Grab our context
    var context = canvas.getContext('2d');
    
    // Make sure we have a valid defintion of requestAnimationFrame
    var requestAnimationFrame =
            window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            function(callback) {
                return setTimeout(callback, 16);
            };
    
    // Let's define our square
    var square = {
        'x': 50,
        'y': 50,
        'width': 10,
        'height': 10,
        'fill': '#000000'
    };
    
    var render = function() {
        // Clear the canvas
        context.clearRect(0, 0, canvas.width, canvas.height);
        
        // Draw the square
        context.beginPath();
        context.rect(square.x, square.y, square.width, square.height);
        context.fillStyle = square.fill;
        context.fill();
        
        //log
        var img_back =  canvas_back.getContext('2d').getImageData(0, 0, W, H);
       var imgData = img_back.data;	
       var x = (Math.round(square.x) + Math.round(square.y)*W) * 4;
        document.getElementById('log').innerHTML = imgData[x]+'+'+imgData[x+1]+'+'+imgData[x+2];
        // Redraw
        requestAnimationFrame(render);
    };
    
    // Start the redrawing process
    render();
    
    var animate = function(prop, val, duration) {
      // The calculations required for the step function
      var start = new Date().getTime();
      var end = start + duration;
      var current = square[prop];
      var distance = val - current;
        
      var step = function() {
        // Get our current...