Using gradient color - Javascript Canvas

Javascript examples for Canvas:Gradient

Description

Using gradient color

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.6.4.js"></script> 
      <style id="compiled-css" type="text/css">

body {float: left;}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){/*from   w  ww.  ja v a  2s  .co m*/
var elem = document.getElementById('colorPicker');
var context = elem.getContext('2d');
var color, hue = [[255,   0,   0 ],[255, 255,   0 ],[  0, 255,   0 ],[  0, 255, 255 ],[  0,   0, 255 ],[255,   0, 255 ],[255,   0,   0],]
gradient = context.createLinearGradient(0, 0, elem.width, 0);
for (var i = 0; i <= 6; i++) {
    color = 'rgb(' + hue[i][0] + ', ' + hue[i][1] + ', ' + hue[i][2] + ')';
    gradient.addColorStop(i * 1/6, color);
    }
gradient2 = context.createLinearGradient(0, 0, 0, elem.height);
gradient2.addColorStop(0, 'rgba(255, 255, 255, 1)');
gradient2.addColorStop(0.01, 'rgba(255, 255, 255, 1)');
gradient2.addColorStop(0.50, 'rgba(255, 255, 255, 0)');
gradient2.addColorStop(0.52, 'rgba(255, 255, 255, 0)');
gradient2.addColorStop(0.75, 'rgba(0, 0, 0, 1)');
gradient2.addColorStop(1, 'rgba(255, 255, 255, 1)');
context.fillStyle = gradient;
context.fillRect(0, 0, 500, 500);
context.fillStyle = gradient2;
context.fillRect(0, 0, 500, 500);
elem.addEventListener('click', function(e) {
    var x = e.clientX; // lame but close enough for now
    var y = e.clientY;
    var data = context.getImageData(x, y, 1, 1).data;
    var rgb = 'rgb(' + data[0] + ',' + data[1] + ',' + data[2] + ')';
    $('#fluidWrap').css({backgroundColor: rgb});
    $('body').css({backgroundColor: rgb});
    $('.content').css({backgroundColor: rgb});
}, false);
    });

      </script> 
   </head> 
   <body>  
      <canvas id="colorPicker" width="300" height="300"></canvas>   
   </body>
</html>

Related Tutorials