【发布时间】:2018-11-19 10:27:12
【问题描述】:
以下代码是更大项目的一部分:
<body>
<canvas id="check" width="35px" height="40px" style="background-color: blue;"></canvas>
</body>
<script>
const check = document.getElementById('check');
const checkCtx = check.getContext('2d');
check.onclick = function() {
drawCheck(checkCtx, 5, 30);
setTimeout(function() {
fadeOut(check);
}, 1000);
setTimeout(function() {
check.style.opacity = "1";
checkCtx.clearRect(0, 0, check.width, check.height);
}, 2000);
check.style.backgroundColor = "blue";
}
function drawCheck(ctx, x, y) {
var x1 = x;
var y1 = y;
var x2 = x1;
var y2 = y1;
var x3 = x1 + 14;
var y3 = y1 + 7;
ctx.beginPath();
ctx.strokeStyle = "green";
ctx.lineCap = "round";
ctx.lineWidth = 5;
ctx.moveTo(x1, y1);
function draw() {
x2++;
y2 += .5;
ctx.lineTo(x2, y2);
ctx.stroke();
if (x2 < x1 + 14) {
requestAnimationFrame(draw);
} else {
function drawNext() {
x3 += .5;
y3 -= 1.5;
ctx.lineTo(x3, y3);
ctx.stroke();
if (x3 < x1 + 24) {
requestAnimationFrame(drawNext);
} else {
return;
}
}
drawNext();
return;
}
}
draw();
}
function fadeOut(obj) {
var opc = 1;
var finish = false;
obj.style.opacity = 1;
function fade() {
opc -= 0.125;
obj.style.opacity = opc + "";
console.log(opc);
if (opc > 0) {
requestAnimationFrame(fade);
}
}
console.log("Wait for it...");
fade();
console.log("Finished!");
}
</script>
如果您查看控制台,您可以看到 fadeOut 函数在 fade 函数结束之前结束。因此,我必须使用多个setTimeout 函数。我的其他功能也有同样的问题。我不想依赖这些,那我怎样才能让代码等到被调用的函数返回呢?
【问题讨论】:
标签: javascript html animation canvas css-animations