how to draw a flower in javascript

Solutions on MaxInterview for how to draw a flower in javascript by the best coders in the world

showing results for - "how to draw a flower in javascript"
Diego
06 Nov 2020
1const ctx = canvas.getContext("2d");
2
3const petal = [
4  [
5    [0, 0],
6    [0.3, -1],
7    [0.7, -1],
8    [1, 0],
9    [0.7, 1],
10    [0.3, 1],
11    [0, 0]
12  ],
13  [
14    [0, 0],
15    [1, 0]
16  ],
17];
18
19function drawPetal(path, width, height) {
20  var i = 0;
21  do { // loop through paths
22    const p = path[i];
23    let j = 0;
24    ctx.moveTo(p[j][0] * width, p[j++][1] * height);
25    while (j < p.length - 1) {
26      ctx.lineTo(p[j][0] * width, p[j++][1] * height);
27    }
28    if (p[j][0] === p[0][0] && p[j][1] === p[0][1]) { // is the path closed ?
29      ctx.closePath();
30    } else {
31      ctx.lineTo(p[j][0] * width, p[j][1] * height)
32    }
33  } while (++i < path.length);
34}
35
36function drawPetals(x, y, count, startAt, petal, width, height) {
37  const step = (Math.PI * 2) / count;
38  ctx.setTransform(1, 0, 0, 1, x, y);
39  ctx.rotate(startAt);
40  for (var i = 0; i < count; i += 1) {
41    drawPetal(petal, width, height);
42    ctx.rotate(step);
43  }
44  ctx.setTransform(1, 0, 0, 1, 0, 0); // restore default
45}
46
47function drawFlower(col, lineWidth, fitScale, petalCount) {
48  ctx.strokeStyle = col;
49  ctx.lineWidth = lineWidth;
50  const size = Math.min(ctx.canvas.width, ctx.canvas.height) * fitScale * 0.5;
51  ctx.beginPath();
52
53  drawPetals(ctx.canvas.width / 2, ctx.canvas.height / 2, 5, -Math.PI / 2, petal, size, size * 0.2);
54  ctx.stroke();
55  ctx.beginPath();
56  ctx.arc(ctx.canvas.width / 2, ctx.canvas.height / 2, size * 0.15, 0, Math.PI * 2);
57  ctx.fillStyle = col;
58  ctx.fill();
59}
60
61
62drawFlower("black", 4, 0.95, 5);