js实现线条运动
使用 Canvas 实现线条动画
Canvas 是 HTML5 提供的绘图 API,适合实现高性能的线条动画。以下是一个简单的线条运动示例:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let position = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(0, position);
ctx.lineTo(canvas.width, position);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.stroke();
position += 1;
if (position > canvas.height) position = 0;
requestAnimationFrame(animate);
}
animate();
使用 SVG 实现线条动画
SVG 是矢量图形标准,可以通过 CSS 或 JavaScript 实现动画效果:
<svg width="400" height="200">
<line x1="0" y1="50" x2="400" y2="50" stroke="red" stroke-width="2">
<animate attributeName="y1" from="50" to="150" dur="2s" repeatCount="indefinite"/>
<animate attributeName="y2" from="50" to="150" dur="2s" repeatCount="indefinite"/>
</line>
</svg>
使用 CSS 动画实现线条运动
纯 CSS 也可以实现简单的线条动画效果:
<div class="line"></div>
<style>
.line {
width: 100%;
height: 2px;
background: linear-gradient(to right, transparent, #000, transparent);
position: relative;
animation: move 2s infinite linear;
}
@keyframes move {
0% { left: -100%; }
100% { left: 100%; }
}
</style>
实现贝塞尔曲线动画
使用 Canvas 实现更复杂的贝塞尔曲线动画:
const canvas = document.getElementById('bezierCanvas');
const ctx = canvas.getContext('2d');
let t = 0;
function drawBezier() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(50, 150);
const cp1x = 100 + Math.sin(t) * 50;
const cp1y = 50 + Math.cos(t) * 50;
const cp2x = 200 + Math.cos(t) * 50;
const cp2y = 150 + Math.sin(t) * 50;
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, 250, 150);
ctx.strokeStyle = 'green';
ctx.lineWidth = 3;
ctx.stroke();
t += 0.02;
requestAnimationFrame(drawBezier);
}
drawBezier();
使用 Three.js 实现 3D 线条动画
对于更复杂的三维线条动画,可以使用 Three.js 库:
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const points = [];
points.push(new THREE.Vector3(-10, 0, 0));
points.push(new THREE.Vector3(0, 10, 0));
points.push(new THREE.Vector3(10, 0, 0));
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({ color: 0x00ff00 });
const line = new THREE.Line(geometry, material);
scene.add(line);
camera.position.z = 30;
function animate() {
requestAnimationFrame(animate);
line.rotation.x += 0.01;
line.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
以上方法提供了从简单到复杂的线条动画实现方案,可以根据项目需求选择合适的方案。Canvas 适合性能要求高的场景,SVG 适合矢量图形需求,CSS 适合简单的 UI 动画,而 Three.js 则适合复杂的 3D 效果。







