Drawing a zigzag

In this recipe, we'll introduce path drawing by iteratively connecting line subpaths to draw a zigzag path.

Drawing a zigzag

How to do it...

Follow these steps to draw a zigzag path:

  1. Define a 2D canvas context and initialize the zigzag parameters:
    window.onload = function(){
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
      
        var startX = 85;
        var startY = 70;
        var zigzagSpacing = 60;
  2. Define the zigzag style and begin the path:
    context.lineWidth = 10;
        context.strokeStyle = "#0096FF"; // blue-ish color
        context.beginPath();
        context.moveTo(startX, startY);
  3. Draw seven connecting zigzag lines and then make the zigzag path ...

Get HTML5 Canvas Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.