In this recipe, we'll draw four triangles and then fill each one with a different fill style. The fill styles available with the HTML5 canvas API are color fills, linear gradients, radial gradients, and patterns.
Follow these steps to draw four triangles, one with a color fill, one with a linear gradient fill, one with a radial gradient fill, and one with a pattern fill:
Create a simple function that draws a triangle:
function drawTriangle(context, x, y, triangleWidth, triangleHeight, fillStyle){ context.beginPath(); 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(); }
Define a 2D canvas context and set the height, width, and y position of our triangles:
window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context ...