Canvas How to - Create gradient color in gray scale








Question

We would like to know how to create gradient color in gray scale.

Answer


<!-- w  w  w  . j  av a 2  s. co m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
$(window).load(function(){
    var ctx = $("#canvas")[0].getContext('2d');
    var image = ctx.getImageData(0, 0, 128, 128);
    var idx = 0;
    for (var y=0; y < 128; ++y) {
        for (var x=0; x < 128; ++x) {
            image.data[idx+0] = 128;
            image.data[idx+1] = 128;
            image.data[idx+2] = 128;
            image.data[idx+3] = (x+y);
            idx += 4;
        }
    }
    ctx.putImageData(image, 0, 0);
});
</script>
</head>
<body>
    <canvas id='canvas' width='128' height='128'></canvas>
</body>
</html>

The code above is rendered as follows: