Radial gradients can be created using the createRadialGradient() method.
It requires a starting point, a start radius, an end point, and an end radius:
let grd=context.createRadialGradient(startX,
startY,
startRadius,
endX,
endY,
endRadius);
Radial gradients are defined by two imaginary circles.
The first imaginary circle is defined by startX, startY, and startRadius.
The second imaginary circle is defined by endX, endY, and endRadius.
We position colors along the radial gradient line using the addColorStop() method.
<html> <head> <script> function drawTriangle(context, x, y, triangleWidth, triangleHeight, fillStyle){ context.beginPath(); //from ww w . ja v a2 s . c o 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; // radial gradient fill (second from right) let centerX = (canvas.width * 3 / 5 + (canvas.width * 3 / 5 - triangleWidth / 2) + (canvas.width * 3 / 5 + triangleWidth / 2)) / 3; let centerY = (triangleY + (triangleY + triangleHeight) + (triangleY + triangleHeight)) / 3; grd = context.createRadialGradient(centerX, centerY, 10, centerX, centerY, 100); grd.addColorStop(0, "red"); grd.addColorStop(0.17, "orange"); grd.addColorStop(0.33, "yellow"); grd.addColorStop(0.5, "green"); grd.addColorStop(0.666, "blue"); grd.addColorStop(1, "violet"); 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>