O'Reilly logo

HTML5 Canvas Cookbook by Eric Rowell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Working with custom shapes and fill styles

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.

Working with custom shapes and fill styles

How to do it...

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:

  1. 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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required