HTML Canvas fillStyle Property fill linear gradient color

Description

HTML Canvas fillStyle Property fill linear gradient color

View in separate window

<html>
    <head>
        <script>
      function drawTriangle(context, x, y, triangleWidth, triangleHeight, fillStyle){
          context.beginPath();//from   w  w  w .  ja  v a2 s  .  c om
          context.moveTo(x, y);
          context.lineTo(x + triangleWidth / 2, y + triangleHeight);
          context.lineTo(x - triangleWidth / 2, y + triangleHeight);
          context.closePath();
          context.fillStyle = fillStyle;
          context.fill();
      }
      
      window.onload = function(){
          var canvas = document.getElementById("myCanvas");
          var context = canvas.getContext("2d");
          
          var grd;
          var triangleWidth = 150;
          var triangleHeight = 150;
          var triangleY = canvas.height / 2 - triangleWidth / 2;
          
          // linear gradient fill (second from left)
          grd = context.createLinearGradient(canvas.width * 2 / 5, triangleY, canvas.width * 2 / 5, triangleY + triangleHeight);
          grd.addColorStop(0, "red"); 
          grd.addColorStop(1, "blue"); 
          drawTriangle(context, canvas.width * 2 / 5, triangleY, triangleWidth, triangleHeight, grd);
          

      };
        </script>
    </head>
    <body>
    <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
    </canvas>
    </body>
</html>



PreviousNext

Related