Draw a zigzag path with lineTo method in JavaScript

Description

The following code shows how to draw a zigzag path with lineTo method.

Example


<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function(){<!--  w  w  w .jav  a2  s . c om-->
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var startX = 85;
var startY = 70;
var zigzagSpacing = 60;

context.lineWidth = 10;
context.strokeStyle = "#0096FF";
context.beginPath();
context.moveTo(startX, startY);

// draw ten lines
for (var n = 0; n < 10; n++) {
var x = startX + ((n + 1) * zigzagSpacing);
var y;

if (n % 2 == 0) { // if n is even...
y = startY + 100;
}
else { // if n is odd...
y = startY;
}
context.lineTo(x, y);
}

context.stroke();
};
</script>
</head>
<body>
<canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
</canvas>
</body>
</html>

Click to view the demo

The code above generates the following result.

Draw a zigzag path with lineTo method in JavaScript