摘要:HTML5源码,Canvas实例,Canvas动画效果
Three.js制作的HTML5 3D螺旋线动画,了解一下Canvas的用法,本例使用了一个JS封装类Three.js,已打包,左上角的滑动条可改变默认参数,生成不一样的螺旋曲线。一些操作DOM的方法兼容。置于window对象下,兼容浏览器的getElementsByClassName方法,使用:$class(class名,父级元素,标签名); //后两个参数可省略。扩展getElementsByTagName方法,支持简单的属性选择器,使用:$tag(tag[属性=属性名],父级元素); //父级元素可省略,支持写上[属性=属性名]附加属性过滤。
<!DOCTYPE html>
<html>
<head>
<title>Canvas 3D Spiral Animation</title>
<style>
#canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id='canvas' width='400' height='400'></canvas>
<script>
// 获取Canvas元素和3D绘图上下文
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 定义动画参数
let angle = 0;
const speed = 0.02; // 旋转速度
const radius = 100; // 螺旋半径
const distance = 2; // 每帧移动的距离
function animate() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 计算x和z坐标
const x = Math.cos(angle) * radius;
const z = Math.sin(angle) * radius;
// 绘制圆点
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
ctx.beginPath();
ctx.fillStyle = 'red';
ctx.arc(centerX + x, centerY - z, 5, 0, 2 * Math.PI);
ctx.fill();
// 更新角度
angle += speed;
// 更新半径
radius += distance;
// 循环调用动画函数
requestAnimationFrame(animate);
}
// 启动动画
animate();
</script>
</body>
</html>