📅  最后修改于: 2023-12-03 15:24:31.727000             🧑  作者: Mango
在 JavaScript 中可以使用 canvas
元素绘制图形,其中就包括椭圆。要让椭圆沿 x 轴移动,可以使用 requestAnimationFrame
方法来进行动画绘制。
canvas
元素并设置其宽高。const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let x = canvas.width / 2; // 初始位置为 canvas 中心
const y = canvas.height / 2;
const radiusX = 100; // x 轴半径为 100
const radiusY = 50; // y 轴半径为 50
const speed = 2; // 每帧移动的距离
let direction = 1; // 移动的方向,1 为向右,-1 为向左
requestAnimationFrame
方法在每一帧绘制椭圆并更新位置。function drawEllipse() {
context.clearRect(0, 0, canvas.width, canvas.height);
// 让椭圆沿 x 轴移动
x += speed * direction;
if (x + radiusX >= canvas.width) {
direction = -1;
} else if (x - radiusX <= 0) {
direction = 1;
}
context.beginPath();
context.ellipse(x, y, radiusX, radiusY, 0, 0, 2 * Math.PI);
context.stroke();
requestAnimationFrame(drawEllipse); // 循环执行
}
drawEllipse();
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let x = canvas.width / 2;
const y = canvas.height / 2;
const radiusX = 100;
const radiusY = 50;
const speed = 2;
let direction = 1;
function drawEllipse() {
context.clearRect(0, 0, canvas.width, canvas.height);
x += speed * direction;
if (x + radiusX >= canvas.width) {
direction = -1;
} else if (x - radiusX <= 0) {
direction = 1;
}
context.beginPath();
context.ellipse(x, y, radiusX, radiusY, 0, 0, 2 * Math.PI);
context.stroke();
requestAnimationFrame(drawEllipse);
}
drawEllipse();