HTML5 Game - Move image pixel

Description

Move image pixel

Demo

ResultView the demo in separate window

<!doctype html>  
   <html>  
    <head>  
     <meta charset="utf-8">  
     <title>Pixel Move</title>  
     <style>canvas{border:1px solid red;}</style>  
    </head>  
    <body>  
     <canvas id="canvas" width="400" height="400"></canvas>
     <script>  
     window.onload = function () {  
       let canvas = document.getElementById('canvas'),  
           context = canvas.getContext('2d'),  
           mouse = captureMouse(canvas);  
     //from  www  .  j a  va2  s. co  m
       (function drawFrame () {  
         window.requestAnimationFrame(drawFrame, canvas);  
     
         //draw some stripes: red, green, and blue  
         for (let i = 0; i < canvas.width; i += 10) {  
           for (let j = 0; j < canvas.height; j += 10) {  
             context.fillStyle = (i % 20 === 0) ? "blue" : ((i % 30 === 0) ? "grey" : "yellow");  
             context.fillRect(i, j, 10, 10);  
           }  
         }  
     
         let imagedata = context.getImageData(0, 0, canvas.width, canvas.height),  
             pixels = imagedata.data;  
     
         //pixel iteration  
         for (let y = 0; y < imagedata.height; y += 1) {  
           for (let x = 0; x < imagedata.width; x += 1) {  
     
             let dx = x - mouse.x,  
                 dy = y - mouse.y,  
                 dist = Math.sqrt(dx * dx + dy * dy),  
                 offset = (x + y * imagedata.width) * 4,  
                 r = pixels[offset],  
                 g = pixels[offset + 1],  
                 b = pixels[offset + 2];  
     
             pixels[offset]     = Math.sin(r * dist * 0.001) * 256;  
             pixels[offset + 1] = Math.cos(g * dist * 0.001) * 256;  
             pixels[offset + 2] = Math.tan(b * dist * 0.0005) * 256;  
           }  
         }  
      context.putImageData(imagedata, 0, 0);  
    }());  
  };  
  function captureMouse(element) {
  let mouse = {x: 0, y: 0, event: null},
      body_scrollLeft = document.body.scrollLeft,
      element_scrollLeft = document.documentElement.scrollLeft,
      body_scrollTop = document.body.scrollTop,
      element_scrollTop = document.documentElement.scrollTop,
      offsetLeft = element.offsetLeft,
      offsetTop = element.offsetTop;
  
  element.addEventListener('mousemove', function (event) {
    let x, y;
    
    if (event.pageX || event.pageY) {
      x = event.pageX;
      y = event.pageY;
    } else {
      x = event.clientX + body_scrollLeft + element_scrollLeft;
      y = event.clientY + body_scrollTop + element_scrollTop;
    }
    x -= offsetLeft;
    y -= offsetTop;
    
    mouse.x = x;
    mouse.y = y;
    mouse.event = event;
  }, false);
  
  return mouse;
}      
  </script>  
 </body>  
</html>

Related Topic