I'm trying to draw a shape on canvas to fill the gradient of the rainbow. The desired result looks something like this:

Creating the shape itself is quite simple, just creating a path and drawing lines. However, actually filling it with a gradient seems somewhat more complicated, since only radial and linear gradients are supported.
The closest I got this:
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var gradient=ctx.createLinearGradient(0,0,0,100); gradient.addColorStop (0, 'red'); gradient.addColorStop (0.25, 'yellow'); gradient.addColorStop (0.5, 'green'); gradient.addColorStop (0.75, 'blue'); gradient.addColorStop (1, 'violet'); ctx.moveTo(0,40); ctx.lineTo(200,0); ctx.lineTo(200,100); ctx.lineTo(0, 50); ctx.closePath(); ctx.fillStyle = gradient; ctx.fill();
<body onload="draw();"> <canvas id="canvas" width="400" height="300"></canvas> </body>
Gradient colors, etc. are correct, but the gradient should, of course, be more triangular, and not rectangular and cropped.
source share