Create a rainbow radial gradient in JavaScript

Description

The following code shows how to create a rainbow radial gradient.

Example


<!DOCTYPE HTML>
<html>
<head>
<script>
function drawTriangle(context, x, y, triangleWidth, triangleHeight, fillStyle){
context.beginPath();<!--   www. j a  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(){
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;

// radial gradient fill (second from right)
var centerX = 300;

var centerY = 100;

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 / 2, triangleY, triangleWidth, triangleHeight, grd);

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

Click to view the demo

The code above generates the following result.

Create a rainbow radial gradient in JavaScript
Home »
  Javascript Tutorial »
    Canvas »
      Canvas Draw
Javascript Tutorial Canvas Draw
Change the stroke style in JavaScript
Clip a region in JavaScript
Control line width in JavaScript
Create Radial Gradient on HTML5 canvas in J...
Create a rainbow radial gradient in JavaScr...
Create linear gradient in JavaScript
Draw an image on HTML5 Canvas in JavaScript
Draw transparent shapes on HTML5 Canvas in ...
Get canvas context in JavaScript
Restore a drawing state in JavaScript
Save and restore Canvas states with button ...
Set color to transparency when drawing on c...
Set shadow color and blur in JavaScript
Use image as the fill pattern in JavaScript