您现在的位置是:网站首页> 编程资料编程资料

前端JS实现太极图案图文示例_JavaScript_

2023-05-24 422人已围观

简介 前端JS实现太极图案图文示例_JavaScript_

正文

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

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

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

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

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

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

绘制黑色圆

下面我们绘制下面的黑色圆,黑色圆的 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(); 

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

// 绘制白色小点 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太极图案的资料请关注其它相关文章!

-六神源码网