温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么用JS实现太极图案

发布时间:2022-09-23 09:39:44 来源:亿速云 阅读:123 作者:iii 栏目:开发技术

这篇文章主要讲解了“怎么用JS实现太极图案”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么用JS实现太极图案”吧!

效果图

怎么用JS实现太极图案

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

怎么用JS实现太极图案

canvas 实现

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

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

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.translate(canvas.width / 2, canvas.height / 2);

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

// 半径
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();

怎么用JS实现太极图案

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

// 绘制左边的半圆
ctx.beginPath();
ctx.fillStyle = '#000';
// 顺时针旋转
ctx.arc(0, 0, radius, -90 * Math.PI / 180, 90 * Math.PI / 180, true)
ctx.fill();

怎么用JS实现太极图案

绘制黑色圆

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

// 绘制下面的黑色圆
ctx.beginPath();
ctx.fillStyle = '#000';
ctx.arc(0, radius / 2, radius / 2, 0, 360 * Math.PI / 180);
ctx.fill();

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

// 绘制上面的白色圆
ctx.beginPath();
ctx.fillStyle = '#fff';
ctx.arc(0, -radius / 2, radius / 2, 0, 360 * Math.PI / 180);
ctx.fill();

怎么用JS实现太极图案

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

// 绘制白色小点
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

*, *::before, *::after {
  margin: 0;
  padding: 0;
}
canvas {
  border: 1px solid #eee;
  background: #ccc;
}

Script

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();

感谢各位的阅读,以上就是“怎么用JS实现太极图案”的内容了,经过本文的学习后,相信大家对怎么用JS实现太极图案这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js
AI