Define a gradient from left to right, as the fill style for the rectangle:
<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="300" height="180" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag.</canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var grd = ctx.createLinearGradient(0, 0, 170, 0); grd.addColorStop(0, "black"); grd.addColorStop(1, "white"); ctx.fillStyle = grd;//from ww w. j a va 2 s . c o m ctx.fillRect(20, 20, 150, 100); </script> </body> </html>
The createLinearGradient()
method creates a linear gradient object.
The gradient can be used to fill rectangles, circles, lines, text, etc.
Use this object as the value to the strokeStyle or fillStyle properties.
Use the addColorStop()
method to specify different colors.
context.createLinearGradient(x0, y0, x1, y1);
Parameter Values
Parameter | Description |
---|---|
x0 | The x-coordinate of the start point of the gradient |
y0 | The y-coordinate of the start point of the gradient |
x1 | The x-coordinate of the end point of the gradient |
y1 | The y-coordinate of the end point of the gradient |