gpt4 book ai didi

javascript - 试图在 Canvas 中实现的CSS动画

转载 作者:行者123 更新时间:2023-11-28 11:05:40 25 4
gpt4 key购买 nike

我正在尝试在我的 Canvas 中实现相同类型的动画...你们能告诉我如何用 Canvas 中圆圈内的文字实现它吗...因为 webkit 在 firefox 或 ie 中不起作用...所以我正在使用 canvas在下面提供我的代码...

 function animate(current) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.arc(x, y, radius, -(quart), ((circ) * current) - quart, false);
context.stroke();
curPerc++;
if (curPerc < endPercent) {
requestAnimationFrame(function () {
animate(curPerc / 100)
});
}
}

最佳答案

只需使用以下代码即可:

var SIZE = 300; 
var SPINNER_WIDTH = 30;
var STEP_PERCENT = 1;
var STEP_DELAY = 20;

var radius, centerX, centerY;
radius = centerX = centerY = SIZE / 2;

var deg360 = Math.PI * 2;
var degStart = -Math.PI / 2;

var canvas = document.getElementById('canvas');
canvas.width = canvas.height = SIZE;
var ctx = canvas.getContext('2d');

var percent = 0;

var animate = function() {
ctx.width = ctx.width; //clear canvas hack

percent += STEP_PERCENT;
var deg = percent / 100 * deg360;

drawArc('#aaa', radius, deg360); //gray backgound circle
drawArc('#0e728e', radius, deg); //blue spinner
drawArc('#fff', radius - SPINNER_WIDTH, deg360); //white center

if (percent >= 100) {
document.getElementById('text').innerText = 'FINISHED';
} else {
setTimeout(animate, STEP_DELAY);
}
}

var drawArc = function(color, arcRadius, deg) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, arcRadius, degStart, degStart + deg, false);
ctx.lineTo(centerX, centerY);
ctx.fill();
}

animate();

您可能想要使用 SIZESPINNER_WIDTHSTEP_PERCENTSTEP_DELAY 伪常量。

Working example on jsFiddle

编辑:

Here is jsFiddle of infinite animation

编辑 2:

这个例子的主要部分是这些代码行:

drawArc('#aaa', radius, deg360);
drawArc('#0e728e', radius, deg);
drawArc('#fff', radius - SPINNER_WIDTH, deg360);

首先我们绘制灰色背景圆,然后绘制蓝色圆弧(deg 是当前度数),最后我们切出一个中心(最初我们的圆弧是实心的)。这些弧线是某种层,一个在另一个之上。

如果你想用另一种颜色做一个半圆,你可以使用 drawArc 调用。例如,您可以在第一行和第二行之间粘贴此代码:

var rightColor = 'green';
drawArc(rightColor, radius, deg360 / 2);

看看jsFiddle

关于javascript - 试图在 Canvas 中实现的CSS动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22270872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com