Canvas drawing lines

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

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();
+4
source share
1 answer

This should be the beginning:

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>
Run codeHide result

x 580 , , , 2 x, 40 . .

+4

Source: https://habr.com/ru/post/1659185/


All Articles