使用HTML5制作一个可以旋转的太极图案交互特效

要制作一个可以旋转的太极图案交互特效,你可以使用HTML5的<canvas>元素结合JavaScript。以下是一个简单的示例,展示了如何实现这个效果:

  1. HTML:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>旋转太极图案</title>
    <style>
        canvas {
            border: 1px solid black;
            display: block;
            margin: 50px auto;
        }
    </style>
</head>
<body>
    <canvas id="taijiCanvas" width="400" height="400"></canvas>
    <script src="script.js"></script>
</body>
</html>
  1. JavaScript (script.js):
const canvas = document.getElementById('taijiCanvas');
const ctx = canvas.getContext('2d');
let rotation = 0;

function drawTaiji() {
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = Math.min(centerX, centerY) - 10;

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.translate(centerX, centerY);
    ctx.rotate(rotation * Math.PI / 180); // 旋转图案

    // 绘制太极的上半部分(白色)
    ctx.beginPath();
    ctx.arc(0, 0, radius, Math.PI, 2 * Math.PI);
    ctx.fillStyle = 'white';
    ctx.fill();

    // 绘制太极的下半部分(黑色)以及小圆点
    ctx.beginPath();
    ctx.arc(0, 0, radius, 0, Math.PI);
    ctx.fillStyle = 'black';
    ctx.fill();

    ctx.beginPath();
    ctx.arc(0, -radius / 2, radius / 4, 0, 2 * Math.PI);
    ctx.fillStyle = 'white';
    ctx.fill();

    ctx.beginPath();
    ctx.arc(0, radius / 2, radius / 4, 0, 2 * Math.PI);
    ctx.fillStyle = 'black';
    ctx.fill();

    ctx.restore();
}

// 初始绘制
drawTaiji();

// 添加鼠标交互来旋转太极图案
canvas.addEventListener('mousemove', (event) => {
    const rect = canvas.getBoundingClientRect();
    const mouseX = event.clientX - rect.left;
    const mouseY = event.clientY - rect.top;
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const dx = mouseX - centerX;
    const dy = mouseY - centerY;
    rotation += Math.atan2(dy, dx) * (180 / Math.PI); // 根据鼠标位置计算旋转角度
    drawTaiji(); // 重新绘制图案
});

这个示例中,我们首先定义了一个HTML结构,其中包含一个<canvas>元素。然后,在JavaScript中,我们定义了一个drawTaiji函数来绘制太极图案,并根据rotation变量来旋转它。最后,我们添加了一个mousemove事件监听器来根据鼠标位置更新rotation变量,并重新绘制图案。

posted @ 2024-12-22 09:24  王铁柱6  阅读(73)  评论(1)    收藏  举报