【问题标题】:Canvas JS - Circle animation that moves to center of screen when page is loadedCanvas JS - 加载页面时移动到屏幕中心的圆形动画
【发布时间】:2020-10-31 20:11:11
【问题描述】:
我想创建一个在页面加载时从页面顶部缓慢移动到页面中间的圆圈;但是,当我加载屏幕时,什么都没有出现。
我认为问题出在我的 move() 函数上,但我不确定。
function move() {
if (y == -75) {
for (let i = y; i < (window.innerHeight / 2); i++) {
requestAnimationFrame(draw);
i += velocity;
velocity += gravity;
}
}
}
我的代码笔:
https://codepen.io/michellevit/pen/jOrxOdE
【问题讨论】:
标签:
javascript
function
animation
canvas
【解决方案1】:
问题在于for 循环没有按照您的预期执行。它们通常不是此类编程的最佳人选。
改为使用递归函数,该函数每次检查状态是什么并不断调用自身直到满足特定条件。
const myCanvas = document.getElementById('myCanvas');
const ctx = myCanvas.getContext('2d');
var canvas = document.getElementsByTagName('canvas')[0];
canvas.width = 400;
canvas.height = window.innerHeight;
let velocity = 0.1;
let gravity = 0.1;
let y = -75;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalAlpha = 0;
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'white';
ctx.globalAlpha = 0.4;
ctx.beginPath();
ctx.arc(200, y, 50, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
}
function move() {
if (y <= (canvas.height / 2)) {
y += velocity;
velocity += gravity;
draw();
requestAnimationFrame(move);
}
}
move();
body,
html {
height: 100%;
}
.bg {
background: blue;
}
section {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
<div class="bg">
<section>
<canvas id="myCanvas"></canvas>
</section>
</div>