How to use the linear gradient on HTML5 canvas

Description

createLinearGradient(x0, y0, x1, y1) creates a linear gradient and return CanvasGradient object.

CanvasGradient object defines the method shown in the following table:

NameDescriptionReturns
addColorStop(position, color)Adds a solid color to the gradient linevoid

Example


<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {<!-- www .j a  v a  2s.c o  m-->
      border: thin solid black;
      margin: 4px
}
</style>
</head>
<body>
      <canvas id="canvas" width="500" height="500"> 
      Your browser doesn't support the <code>canvas</code> element 
      </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





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window