Mit addColorStop() den Farbverlauf definieren.
function draw() {
var canvas = document.getElementById('canvas');
if(canvas && canvas.getContext) {
var ctx = canvas.getContext('2d');
if(ctx) {
// Farbverlauf definieren
var fill = ctx.createLinearGradient(0, 0, 0, canvas.height - 1);
fill.addColorStop(0.0, 'yellow'); // Gelb
fill.addColorStop(0.5, '#ff0000'); // Rot
fill.addColorStop(1.0, 'rgb(0,0,255)'); // Blau
// Füllfarbe setzen
ctx.fillStyle = fill;
// Rechteck mit Farbverlauf zeichnen
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
}
}// draw()
window.onload = draw;
<canvas id="canvas" width="450" height="300"> <p>Dieses Beispiel benötigt einen Webbrowser mit aktivierter <a href="http://de.wikipedia.org/wiki/Canvas_(HTML-Element)">HTML Canvas</a>-Unterstützung.</p> </canvas> <noscript> <p>Dieses Beispiel benötigt einen Webbrowser mit aktivierter <a href="http://de.wikipedia.org/wiki/JavaScript">JavaScript</a>-Unterstützung.</p> </noscript>