Mit createLinearGradient() einen Farbverlauf definieren und
diesen im richtigen Bereich anwenden.
function draw() {
var canvas = document.getElementById('canvas');
if(canvas && canvas.getContext) {
var ctx = canvas.getContext('2d');
if(ctx) {
// Hintergrund Weiß
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Ursprung verschieben
ctx.translate(20, canvas.height - 30);
ctx.scale(1, -1);
// Farbverlauf
var fill = ctx.createLinearGradient(0, 0, 0, 120);
fill.addColorStop(0.0, 'red');
fill.addColorStop(1.0, 'blue');
// Füllfarbe setzen
ctx.fillStyle = fill;
// Rechtecke mit Farbverlauf zeichnen
ctx.fillRect( 0, 0, 30, 90);
ctx.fillRect(40, 0, 30, 120);
// Außerhalb des mit createLinearGradient(0, 0, 0, 120)
// definierten Bereichs. Daher sind dieses Rechtecke
// teilweise bzw. ganz ohne Farbverlauf.
ctx.fillRect( 80, 75, 30, 120);
ctx.fillRect(120, 140, 30, 120);
}
}
}// draw()
window.onload = draw;
<canvas id="canvas" width="250" 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>