How to use HTML5 Canvas Linear Gradient

This article describe about HTML5 Canvas Linear Gradient.
  • 2459

HTML5 Canvas Linear Gradient

We can use the createLinearGradient() method for create linear gradient in HTML5. It is defined by imaginary line that defines the direction of the gradient. After created gradient we can insert colors using the addColorStop property.

<script>
var grad = context.createLinearGradient(startX, startY, endX, endY);
grad.addColorStop(offset, color);
</script>

HTML5 Canvas Linear Gradient Example

<!DOCTYPE HTML>

<html>

  <head>

    <style>

      body {

        margin: 0px;

        padding: 0px;

      }

      #myCanvas {

        border: 1px solid #9C9898;

      }

    </style>

    <script>

        window.onload = function () {

            var canvas = document.getElementById("myCanvas");

            var context = canvas.getContext("2d");

            context.beginPath();

            context.moveTo(170, 80);

            context.bezierCurveTo(120, 100, 130, 150, 230, 150);

            context.bezierCurveTo(250, 180, 320, 180, 340, 150);

            context.bezierCurveTo(420, 140, 420, 120, 390, 100);

            context.bezierCurveTo(430, 40, 370, 30, 340, 50);

            context.bezierCurveTo(320, 5, 220, 20, 250, 50);

            context.bezierCurveTo(200, 5, 150, 20, 170, 80);

            context.closePath();

            var grad = context.createLinearGradient(230, 0, 370, 200);

            grad.addColorStop(0, "yellow");

            grad.addColorStop(1, "Gray");

            context.fillStyle = grad;

            context.fill();

            context.lineWidth = 4;

            context.strokeStyle = "red";

            context.stroke();

        };

 

    </script>

  </head>

  <body>

    <canvas id="myCanvas" width="578" height="210"></canvas>

  </body>

</html>

 

Output


linear gradient pic1.jpg

Further Readings

You may also want to read these related articles :

  • HTML5 article

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.