Horizontal gradient on a complex shape
<!DOCTYPE html> <html> <head> <style> #canvas { /*ww w.ja v a2 s . com*/ border:1px solid #03F; background:#CFC; } </style> </head> <body> <canvas id="canvas" width="640" height="480"></canvas> <script> let context = document.getElementById('canvas').getContext('2d'); let gr = context.createLinearGradient(0, 0, 100, 0); // Add the color stops. gr.addColorStop(0,'rgb(255,0,0)'); gr.addColorStop(.5,'rgb(0,255,0)'); gr.addColorStop(1,'rgb(255,0,0)'); // Use the gradient for the fillStyle. context.fillStyle = gr; context.beginPath(); context.moveTo(0,0); context.lineTo(50,0); context.lineTo(100,50); context.lineTo(50,100); context.lineTo(0,100); context.lineTo(0,0); context.stroke(); context.fill(); context.closePath(); </script> </body> </html>