Brandy Kimmel Brandy Kimmel - 1 month ago 6
HTML Question

Drawing lines for Canvas

I am kind of new to all this and cannot seem to figure out how to make a for loop (if possible) that will draw the type of line I am looking for. I am trying to create an image of a pumpkin using canvas and want to outline the teeth. I was hoping there was an easier way than typing out all of the code to draw the individual lines it takes to outline the teeth. Here is the code for each individual line, but I cannot seem to figure out the for loop that would do the same thing. Any help would be greatly appreciated. Thanks.

context.beginPath();
context.strokeStyle = '#cc5200';
context.moveTo(220, 590);
context.lineTo(220, 550);
context.moveTo(220, 550);
context.lineTo(260, 550);
context.moveTo(260, 550);
context.lineTo(260, 590);
context.moveTo(260, 590);
context.lineTo(300, 590);
context.moveTo(300, 590);
context.lineTo(300, 550);
context.moveTo(300, 550);
context.lineTo(340, 550);
context.moveTo(340, 550);
context.lineTo(340, 590);
context.moveTo(340, 590);
context.lineTo(380, 590);
context.moveTo(380, 590);
context.lineTo(380, 550);
context.moveTo(380, 550);
context.lineTo(420, 550);
context.moveTo(420, 550);
context.lineTo(420, 590);
context.moveTo(420, 590);
context.lineTo(460, 590);
context.moveTo(460, 590);
context.lineTo(460, 550);
context.moveTo(460, 550);
context.lineTo(500, 550);
context.moveTo(500, 550);
context.lineTo(500, 590);
context.moveTo(500, 590);
context.lineTo(540, 590);
context.moveTo(540, 590);
context.lineTo(540, 550);
context.moveTo(540, 550);
context.lineTo(580, 550);
context.lineTo(580, 590);

context.stroke();

Answer

This should be a start:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

context.beginPath();
context.strokeStyle = '#cc5200';

// Example line that is repeated in the loop
context.moveTo(10, 90);      // Bottom left
context.lineTo(10, 50);      // Up
context.lineTo(10 + 40, 50); // Right
context.lineTo(10 + 40, 90); // Down
context.lineTo(10 + 80, 90); // Right

context.moveTo(220, 90);
for (var i = 220; i <= 540; i += 80) {
  context.lineTo(i, 90);
  context.lineTo(i, 50);
  context.lineTo(i + 40, 50);
  context.lineTo(i + 40, 90);
  if(i != 540) // Don't draw the line for the last one
    context.lineTo(i + 80, 90);
}


context.stroke();
<canvas id="canvas" width="600" height="600"></canvas>

x values of 580 aside, you seem to be drawing 2 lines for each x coordinate, 40 pixels apart. Those steps can be put into a loop.

Comments