JavaScript画布:乒乓动画
我是HTML5+画布游戏开发人员的新手。尝试在我的乒乓球游戏中设置球的动画。这是我的。相关片段: 增加球的速度:JavaScript画布:乒乓动画,javascript,html,canvas,html5-canvas,Javascript,Html,Canvas,Html5 Canvas,我是HTML5+画布游戏开发人员的新手。尝试在我的乒乓球游戏中设置球的动画。这是我的。相关片段: 增加球的速度: Ball.prototype.update = function () { this.x += this.velocity.x; this.y += this.velocity.y; }; 游戏循环代码: function update() { ball.update(); window.requestAnimationFrame(update);
Ball.prototype.update = function () {
this.x += this.velocity.x;
this.y += this.velocity.y;
};
游戏循环代码:
function update() {
ball.update();
window.requestAnimationFrame(update);
}
球就在那里。我在谷歌上搜索过,读过好几篇文章,但运气不好。如果有人能帮我让球移动,我将不胜感激
删除了render()
函数,因为不需要(将所有内容移动到update()
),您需要
- 清除画布以重新绘制
- 在画布上的每个关键帧上再次“渲染”所有更新的元素对象(不仅仅在init上)
您没有清除画布以重新绘制。您可以执行
canvas.width=canvas.width
而不是clearRect
。我听说它更快,但可能只是更容易记住,或者更短,我不记得了。。。抱歉,这可能是一种不好的做法,clearRect的速度要快得多,而且将画布宽度设置为自身也有一个额外的副作用:它会清除所有画布状态。我使用我在代码中创建的一个小1像素图像(或几个像素,如果我需要渐变),用drawImage(背景,0,0,canvas.width,canvas.height)清除画布
与clearRect一样快(如果不是更快的话),并且可以更好地控制背景。在不需要额外GPU时间的情况下,使用平滑的渐变而不是平淡的颜色非常方便。AFAIK清除画布的快速方法是只清除需要清除的PX,这些都是旧的移动元素位置+大小。在绘制一些移动的球时,不需要任何优化。只需编写干净的代码。
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
function init(width, height, bg) {
canvas.width = width;
canvas.height = height;
canvas.style.backgroundColor = bg;
document.body.appendChild(canvas);
function Paddle(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.velocity = {
x: 0,
y: 0
};
}
Paddle.prototype.render = function () {
ctx.fillStyle = 'rgb(2, 149, 212)';
ctx.fillRect(this.x, this.y, this.width, this.height);
};
function Player() {
this.paddle = new Paddle(485, canvas.height / 2 - 25, 15, 50);
}
Player.prototype.render = function () {
this.paddle.render();
};
function AI() {
this.paddle = new Paddle(0, canvas.height / 2 - 25, 15, 50);
}
AI.prototype.render = function () {
this.paddle.render();
};
function Ball(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
this.velocity = {
x: 2,
y: 2
};
}
Ball.prototype.render = function () {
ctx.beginPath();
ctx.fillStyle = 'rgb(80, 80, 80)';
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fill();
};
Ball.prototype.update = function () {
this.x += this.velocity.x;
this.y += this.velocity.y;
};
window.player = new Player();
window.computer = new AI();
window.ball = new Ball(canvas.width / 2, canvas.height / 2, 10);
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
player.render();
computer.render();
ball.update();
ball.render();
window.requestAnimationFrame(update);
}
function main() {
init(500, 250, '#EEE');
update();
}
main();