我一直在学习一些javascript / canvas动画,但我无法让这个动画正常工作。
我的目标是动画将在顶部开始绘制,然后当它返回到顶部时它将停止前进并且起始位置将在弧周围前进,使其看起来好像它正在擦除自身并且一旦在顶部(1.5 * PI)将再次开始绘制。
这是一个小提琴:https://jsfiddle.net/kg1fmsjj/
这是我的代码:
function f(element, colour, thickness, elapsedTime) {
// Create Element
element.innerHTML = '';
var canvas = document.createElement('canvas');
var context = canvas.getContext("2d");
element.appendChild(canvas);
// Circle Params
context.lineWidth = thickness;
context.strokeStyle = colour;
var width = canvas.width;
var height = canvas.height;
var mathPi = Math.PI;
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 40;
var startAngle = 1.5 * mathPi;
var endAngle = 1.5 * mathPi;
context.lineWidth = thickness;
context.strokeStyle = colour;
var erasing = false;
function animate() {
if(erasing) {
startAngle = startAngle + 0.01 * mathPi;
} else {
endAngle = endAngle + 0.01 * mathPi;
}
if (endAngle > (1.5 * mathPi)) {
erasing = true;
}
if (startAngle > (1.5 * mathPi)) {
erasing = false;
}
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, false);
context.stroke();
context.closePath();
}
setInterval(animate, 10);
}
f(document.getElementById('out'), '#800080', 4, 60);
答案 0 :(得分:2)
context.arc
可让您选择逆时针绘制圆弧。
此功能可让您创建所需的效果:
以下是示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
ctx.lineWidth=2;
ctx.strokeStyle='#800080';
var PI=Math.PI;
var cx=cw/2;
var cy=ch/2;
var radius=cw/2-30;
var angle=0;
var direction=1;
requestAnimationFrame(animate);
function animate(time){
ctx.clearRect(0,0,cw,ch);
angle+=PI/120;
if(angle<0 || angle>PI*2){
angle=0;
direction*=-1;
}
draw();
requestAnimationFrame(animate);
}
function draw(){
var counterclockwise=(direction>0)?false:true;
var s=-Math.PI/2;
var e=angle-Math.PI/2;
ctx.beginPath();
ctx.arc(cx,cy,radius,s,e,counterclockwise);
ctx.stroke();
}
&#13;
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;
答案 1 :(得分:1)
您需要使用clearRect()方法清除每次重绘的画布。
切换删除变量时需要更改条件。如果擦除并且startAngle&gt; = endAngle则切换擦除变量。如果没有擦除并且endAngle&gt; = startAngle + 2 * PI则切换擦除变量。
然后animate()方法变为......
function animate() {
if(erasing) {
startAngle = startAngle + 0.01 * mathPi;
if (startAngle >= endAngle) {
erasing = false;
}
} else {
endAngle = endAngle + 0.01 * mathPi;
if (endAngle >= startAngle + 2.0 * mathPi) {
erasing = true;
}
}
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, false);
context.stroke();
}