HTML Canvas Image Color Spray Paint

Description

HTML Canvas Image Color Spray Paint

View in separate window

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Spray Paint</title>
  </head>/*  w ww.j a v  a2s. c om*/
  <body>
    <canvas id="canvas" width="400" height="400"></canvas>
    <aside>Click and draw with the mouse.</aside>
    <script>
captureMouse = function (element) {
  var 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) {
    var 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;
};
    window.onload = function () {
      var 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 = "red";
        canvas.addEventListener('mousemove', onMouseMove, false);
      }, false);

      canvas.addEventListener('mouseup', function () {
        canvas.removeEventListener('mousemove', onMouseMove, false);
      }, false);

      function onMouseMove () {
        //loop over each brush bristle
        for (var i = 0; i < brush_density; i++) {
          var angle = Math.random() * Math.PI * 2,
              radius = Math.random() * brush_size,
              xpos = (mouse.x + Math.cos(angle) * radius) | 0,
              ypos = (mouse.y + Math.sin(angle) * radius) | 0,
              offset = (xpos + ypos * imagedata.width) * 4; //array index of canvas coordinate

          //set the color of a pixel using its 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);
      }
    };
    </script>
  </body>
</html>



PreviousNext

Related