"使用 Canvas 制作无人机旋转特效
<canvas id=\"canvas\" width=\"400\" height=\"400\"></canvas>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 设置无人机的属性
const drone = {
x: canvas.width / 2, // 无人机的初始 x 坐标
y: canvas.height / 2, // 无人机的初始 y 坐标
width: 50, // 无人机的宽度
height: 30, // 无人机的高度
rotation: 0, // 无人机的初始旋转角度(弧度)
rotationSpeed: 0.02 // 无人机的旋转速度
};
function drawDrone() {
ctx.save(); // 保存画布的当前状态
// 平移画布,使无人机的中心与画布的中心重合
ctx.translate(drone.x, drone.y);
// 旋转画布,实现无人机的旋转效果
ctx.rotate(drone.rotation);
// 绘制无人机的机身
ctx.fillStyle = 'gray';
ctx.fillRect(-drone.width / 2, -drone.height / 2, drone.width, drone.height);
// 绘制无人机的机翼
ctx.fillStyle = 'lightgray';
ctx.beginPath();
ctx.moveTo(-drone.width / 2, -drone.height / 2);
ctx.lineTo(-drone.width / 2, drone.height / 2);
ctx.lineTo(-drone.width / 2 - 10, 0);
ctx.closePath();
ctx.fill();
ctx.restore(); // 恢复画布的状态
}
function update() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 更新无人机的旋转角度
drone.rotation += drone.rotationSpeed;
// 绘制无人机
drawDrone();
// 请求下一帧动画
requestAnimationFrame(update);
}
// 启动动画
update();
以上代码使用 Canvas 绘制了一个简单的无人机旋转特效。首先,我们在 HTML 中创建了一个 Canvas 元素,然后在 JavaScript 中获取到该元素的上下文对象。接下来,我们定义了无人机的属性,包括位置、尺寸、旋转角度和旋转速度等。然后,我们定义了一个绘制无人机的函数,其中使用了 save() 和 restore() 方法来保存和恢复画布的状态,以避免旋转影响其他绘制。在 drawDrone() 函数中,我们使用矩形和路径绘制了无人机的机身和机翼。最后,在 update() 函数中,我们使用 clearRect() 方法清除画布,然后更新无人机的旋转角度,调用 drawDrone() 函数绘制无人机,最后使用 requestAnimationFrame() 方法请求下一帧动画,实现无人机的旋转效果。
通过以上代码,我们可以在 Canvas 中制作一个简单的无人机旋转特效。你可以根据需要自定义无人机的尺寸、颜色和旋转速度等属性,从而实现不同的效果。希望这对你有所帮助!"