HTML5 Game - Spray paint effect

Description

Spray paint effect

Demo

ResultView the demo in separate window

<!doctype html>  
<html>  
 <head>  
  <meta charset="utf-8">  
  <title>Spray Paint</title>  
  <style>canvas{border:1px solid red;}</style>  
 </head>  /*from   w  ww .  java 2 s .c om*/
 <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),  
        imagedata = context.getImageData(0, 0, canvas.width, canvas.height),  
        pixels = imagedata.data,  
        brush_size = 25,  
        brush_density = 50,  
        brush_color;  
          
    canvas.addEventListener('mousedown', function () {  
      brush_color = 12;
      canvas.addEventListener('mousemove', onMouseMove, false);  
    }, false);  
  
    canvas.addEventListener('mouseup', function () {  
      canvas.removeEventListener('mousemove', onMouseMove, false);  
    }, false);  
          
    function onMouseMove () {  
      //loop over each brush point  
      for (let i = 0; i < brush_density; i++) {  
        let angle = Math.random() * Math.PI * 2,  
            radius = Math.random() * brush_size,  
            xpos = (mouse.x + Math.cos(angle) * radius) | 0, //remove decimal  
                ypos = (mouse.y + Math.sin(angle) * radius) | 0,  
                offset = (xpos + ypos * imagedata.width) * 4;  

            //pixel component colors: r,g,b,a (0-255)  
            pixels[offset]     = brush_color >> 16 & 0xff; //red  
            pixels[offset + 1] = brush_color >> 8 & 0xff;  //green  
            pixels[offset + 2] = brush_color & 0xff;       //blue  
            pixels[offset + 3] = 255;                      //alpha  
          }  

          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