Create linear gradient in JavaScript

Description

The following code shows how to create linear gradient.

Example


<!--from w  ww .j  a  v  a2  s.co m-->
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas id="canvas" width="500" height="500">
</canvas>
<script>
var ctx = document.getElementById("canvas").getContext("2d");
var grad = ctx.createLinearGradient(0, 0, 500, 140);
grad.addColorStop(0.2, "red");
grad.addColorStop(0.5, "white");
grad.addColorStop(1, "black");
ctx.fillStyle = grad;
ctx.fillRect(0, 20, 500, 140);
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Create linear gradient in JavaScript
Home »
  Javascript Tutorial »
    Canvas »
      Canvas Draw
Javascript Tutorial Canvas Draw
Change the stroke style in JavaScript
Clip a region in JavaScript
Control line width in JavaScript
Create Radial Gradient on HTML5 canvas in J...
Create a rainbow radial gradient in JavaScr...
Create linear gradient in JavaScript
Draw an image on HTML5 Canvas in JavaScript
Draw transparent shapes on HTML5 Canvas in ...
Get canvas context in JavaScript
Restore a drawing state in JavaScript
Save and restore Canvas states with button ...
Set color to transparency when drawing on c...
Set shadow color and blur in JavaScript
Use image as the fill pattern in JavaScript