Canvas 上移一张图片花了太多时间

Canvas Taking too much time to move a picture up

我正在尝试移动 <canvas> 上的图片进行跳转。

index.html

<!DOCTYPE html>
<html>
<head>
<title>Ball Jump</title>
</head>
<body>
<img src="./assets/ball.png" height="0px" width="0px" id="ball">
<br>


<br>
<canvas height="210px" width="350px" id="paper" onclick="play()"></canvas>
<script type="text/javascript" src="./main.js"></script
</body>
</html>

main.js

'use strict'
var paper = document.getElementById('paper');
var ball = document.getElementById('ball');
var brush = paper.getContext('2d');
brush.drawImage(dino, 0, 150, 70, 50);
var y = 150;
function play() {
up();
function up() {
if (y > 50) {
brush.clearRect(0, y-1, 70, y+50);
brush.drawImage(ball, 0, y, 70, 50);
y--;
}
else { clearInterval(jump); }
}
var jump = setInterval(up, 10);
function down() {
if (y < 150) {
brush.clearRect(0, y-1, 70, y+50);
brush.drawImage(ball, 0, y, 70, 50);
y++;
}
else { clearInterval(fall); }
}
var fall = setInterval(down, 10);
}

但问题是球是滞后的,需要更多时间才能上升,但即使两个函数都设置为 10 毫秒,它也能正常下降。 请帮忙!!!

为了在浏览器上流畅地播放动画运行,你真的应该使用 requestAnimationFrame 循环而不是 setInterval

在此处查看示例: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations

原因如下: .

我认为你应该使用 requestAnimationFrame 而不是 setInterval

例子

const canvas = document.querySelector('#canvas');
const context = canvas.getContext('2d');

const image = new Image();
image.src = "https://picsum.photos/seed/picsum/50/50";

image.addEventListener("load", load);

function load(event) {
  loop();
}

let x = 0;
let y = 0;
let t = 0;
let r = 50;
const inc = Math.PI/90;

function loop() {
  const width = canvas.width;
  const height = canvas.height;
  context.clearRect(0, 0, width, height);
  context.drawImage(image, x, y, image.width, image.height);
  
  x = 100 + r * Math.cos(t);
  y = 100 + r * Math.sin(t);
  t = t + inc;
  
  requestAnimationFrame(loop);
}
<canvas height="400px" width="400px" id="canvas"></canvas>

我不会使用多个 setInterval 一个应该做...
这是一个例子:

var paper = document.getElementById('paper');
var brush = paper.getContext('2d');
var y = 100;
var speed = 1;

function draw() {
  if ((y < 10) || (y > 150)) {
    speed *= -1
  }
  y += speed
  brush.clearRect(0, 0, 160, 300);
  brush.fillRect(10, y, 10, 10);
}

function play() {
  setInterval(draw, 10);
}

draw()
<canvas height="160" width="300" id="paper" onclick="play()"></canvas>

在您的代码中,两个时间间隔同时 运行,这可能会导致您看到对象滞后的奇怪行为,需要更多时间才能上升但下降没问题。

我引入了变量 speed 来代替两个 setInterval 来确定运动的方向,当位置超过我们的时,我们将 "flip" 它 speed *= -1边界

...在您的 canvas 动画中使用此模式,如果性能变得至关重要,则很容易过渡到 requestAnimationFrame,但对于像这样的简单练习代码,setInterval 工作正常。