JavaScript
主页 > 网络编程 > JavaScript >

前端JS实现太极图案图文介绍

2022-09-23 | 佚名 | 点击:

正文

本篇我们实现一个看似复杂毫无头绪,但实际上简单无比的图形,就是下图的太极图案

刚看到这个图案时候可能毫无头绪,因为各种圆弧,在实现时甚至都不知道应该用什么函数,但如果我们换一种样式,看起来是不是简单很多:

我们这次不使用 HTML + CSS 实现该图案,改用 canvas 来弄。

canvas 实现

1

<canvas id="canvas" width="600" height="600"></canvas>

为了方便后续绘制,我们可以将 canvas 的坐标原点从左上角移到 canvas 的中心点

1

2

3

const canvas = document.getElementById('canvas');

const ctx = canvas.getContext('2d');

ctx.translate(canvas.width / 2, canvas.height / 2);

首先我们绘制右侧的半圆,arc 方法的入参除了圆心、半径、弧度外,还可以设置是顺时针还是逆时针的方式从从开始角度画到结束角度。

1

2

3

4

5

6

7

8

// 半径

const radius = 150;

// 绘制右边的半圆

ctx.beginPath();

ctx.fillStyle = '#fff';

// false 表示顺时针旋转

ctx.arc(0, 0, radius, -90 * Math.PI / 180, 90 * Math.PI / 180, false)

ctx.fill();

按照同样的方式,我们完成左侧的黑色半圆

1

2

3

4

5

6

// 绘制左边的半圆

ctx.beginPath();

ctx.fillStyle = '#000';

// 顺时针旋转

ctx.arc(0, 0, radius, -90 * Math.PI / 180, 90 * Math.PI / 180, true)

ctx.fill();

绘制黑色圆

下面我们绘制下面的黑色圆,黑色圆的 Y 轴其实就是半径的一半

1

2

3

4

5

// 绘制下面的黑色圆

ctx.beginPath();

ctx.fillStyle = '#000';

ctx.arc(0, radius / 2, radius / 2, 0, 360 * Math.PI / 180);

ctx.fill();

而上面白色圆的 Y 轴也同样是半径的一半,只不过是负数

1

2

3

4

5

// 绘制上面的白色圆

ctx.beginPath();

ctx.fillStyle = '#fff';

ctx.arc(0, -radius / 2, radius / 2, 0, 360 * Math.PI / 180);

ctx.fill();

看着是不是有那么点感觉了?剩下的就简单很多了,依照两个小圆,在同样的圆心画两个更小的圆:

1

2

3

4

5

6

7

8

9

10

// 绘制白色小点

ctx.beginPath();

ctx.fillStyle = '#fff';

ctx.arc(0, radius / 2, 10, 0, 360 * Math.PI / 180);

ctx.fill();

// 绘制黑色小点

ctx.beginPath();

ctx.fillStyle = '#000';

ctx.arc(0, -radius / 2, 10, 0, 360 * Math.PI / 180);

ctx.fill();

如此便实现我们最终的效果。

完整DEMO

Style

1

2

3

4

5

6

7

8

*, *::before, *::after {

  margin: 0;

  padding: 0;

}

canvas {

  border: 1px solid #eee;

  background: #ccc;

}

Script

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

const canvas = document.getElementById('canvas');

const ctx = canvas.getContext('2d');

ctx.translate(canvas.width / 2, canvas.height / 2);

// 半径

const radius = 150;

// 绘制右边的半圆

ctx.beginPath();

ctx.fillStyle = '#fff';

// 顺时针旋转

ctx.arc(0, 0, radius, -90 * Math.PI / 180, 90 * Math.PI / 180, false)

ctx.fill();

// 绘制左边的半圆

ctx.beginPath();

ctx.fillStyle = '#000';

// 顺时针旋转

ctx.arc(0, 0, radius, -90 * Math.PI / 180, 90 * Math.PI / 180, true)

ctx.fill();

// 绘制下面的黑色圆

ctx.beginPath();

ctx.fillStyle = '#000';

ctx.arc(0, radius / 2, radius / 2, 0, 360 * Math.PI / 180);

ctx.fill();

// 绘制白色小点

ctx.beginPath();

ctx.fillStyle = '#fff';

ctx.arc(0, radius / 2, 10, 0, 360 * Math.PI / 180);

ctx.fill();

// 绘制上面的白色圆

ctx.beginPath();

ctx.fillStyle = '#fff';

ctx.arc(0, -radius / 2, radius / 2, 0, 360 * Math.PI / 180);

ctx.fill();

// 绘制黑色小点

ctx.beginPath();

ctx.fillStyle = '#000';

ctx.arc(0, -radius / 2, 10, 0, 360 * Math.PI / 180);

ctx.fill();

原文链接:https://juejin.cn/post/7145513685392293896
相关文章
最新更新