js实现妖怪
JavaScript 实现妖怪效果
要实现妖怪效果,可以通过动画、变形和随机行为来模拟妖怪的运动和外观。以下是几种实现方式:

使用 Canvas 绘制妖怪
const canvas = document.getElementById('monsterCanvas');
const ctx = canvas.getContext('2d');
function drawMonster(x, y) {
ctx.fillStyle = 'green';
ctx.beginPath();
ctx.arc(x, y, 30, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(x - 10, y - 10, 5, 0, Math.PI * 2);
ctx.arc(x + 10, y - 10, 5, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.arc(x, y + 5, 10, 0, Math.PI);
ctx.stroke();
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
drawMonster(x, y);
requestAnimationFrame(animate);
}
animate();
使用 CSS 动画创建妖怪效果
<div class="monster"></div>
<style>
.monster {
width: 60px;
height: 60px;
background-color: purple;
border-radius: 50%;
position: absolute;
animation: move 3s infinite alternate;
}
@keyframes move {
0% { transform: translateX(0) rotate(0deg); }
100% { transform: translateX(300px) rotate(360deg); }
}
</style>
使用 Three.js 创建 3D 妖怪
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 geometry = new THREE.SphereGeometry(1, 32, 32);
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const monster = new THREE.Mesh(geometry, material);
scene.add(monster);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
monster.rotation.x += 0.01;
monster.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
实现妖怪随机行为
class Monster {
constructor() {
this.x = 0;
this.y = 0;
this.speed = 2;
}
move() {
this.x += (Math.random() - 0.5) * this.speed;
this.y += (Math.random() - 0.5) * this.speed;
}
}
const monster = new Monster();
setInterval(() => {
monster.move();
console.log(`Monster position: (${monster.x}, ${monster.y})`);
}, 100);
这些方法可以根据需求组合使用,创造出更复杂的妖怪效果。






