When I was learning 2D and Canvas in Javascript, I was wondering how to draw a triangle with degraded fill, like a vision field for an enemy in a game. Here is the answer:
How to draw a triangle with degraded fill in Canvas
Take a look at the next Javascript function called draw()
, note the comments inside.
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
// Determine the triangle
ctx.beginPath();
ctx.moveTo(400,0);
ctx.lineTo(0,250);
ctx.lineTo(400,500);
// Determine the degraded fill and its colors
var lingrad = ctx.createLinearGradient(200,250,400,250);
lingrad.addColorStop(0, '#00EBAB');
lingrad.addColorStop(0.9, '#000')
// Combine
ctx.fillStyle = lingrad;
ctx.fill();
} // Else Browser not compatible with Canvas
}
draw();
Check out the demo available on JsFiddle.
Feel free to leave your comment!