Linear gradients can be created with the createLinearGradient() method.
It is defined by a start point and an end point:
let grd=context.createLinearGradient(startX,startY,endX,endY);
We can set the colors of the gradient using the addColorStop() method.
We assign a color value at an offset position along the gradient line from 0 to 1 using addColorStop() method:
grd.addColorStop(offset,color);
Colors with an offset value of 0 is positioned at the starting point of the linear gradient.
Colors with an offset value of 1 is positioned at the end point of the linear gradient.
<html> <head> <script> function drawTriangle(context, x, y, triangleWidth, triangleHeight, fillStyle){ context.beginPath(); /*from www .ja v a 2 s . co m*/ 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(){ let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d"); let grd; let triangleWidth = 150; let triangleHeight = 150; let 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, "#8ED6FF"); // light blue grd.addColorStop(1, "#004CB3"); // dark blue drawTriangle(context, canvas.width * 1 / 5, triangleY, triangleWidth, triangleHeight, grd); }; </script> </head> <body> <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"> </canvas> </body> </html>