A canvas globalCompositeOperation gradient example













var compositeTypes = [
  'source-over','source-in','source-out','source-atop',
  'destination-over','destination-in','destination-out','destination-atop',
  'lighter','darker','copy','xor'
];
function canvasReady() {
  draw();
}
function draw() {
  for (var i=0;i<compositeTypes.length;i++){
    var label = document.createTextNode(compositeTypes[i]);
    document.getElementById('lab'+i).appendChild(label);
    var ctx = document.getElementById('tut'+i).getContext('2d');

    var grad1 = ctx.createLinearGradient(15,15, 70,70);
    grad1.addColorStop(0,    'yellow');
    grad1.addColorStop(0.25, 'red');
    grad1.addColorStop(0.75, 'blue');
    grad1.addColorStop(1,    'limegreen');

    // draw rectangle
    ctx.lineWidth = 10;
    ctx.fillStyle = grad1;
    ctx.fillRect(15,15,70,70);

    // set composite property
    ctx.globalCompositeOperation = compositeTypes[i];

    var grad2 = ctx.createRadialGradient(75,75,5,75,75,35);
    grad2.addColorStop(0,    'yellow');
    grad2.addColorStop(0.25, 'red');
    grad2.addColorStop(0.75, 'blue');
    grad2.addColorStop(1,    'limegreen');
    ctx.fillStyle = grad2;

    // draw circle
    ctx.beginPath();
    ctx.arc(75,75,35,0,Math.PI*2,true);
    ctx.fill();
  }
}