Javascript画布动画弧线

jon*_*sen 1 javascript canvas

我一直在学习一些 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);
Run Code Online (Sandbox Code Playgroud)

mar*_*rkE 5

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();
}
Run Code Online (Sandbox Code Playgroud)
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas" width=300 height=300></canvas>
Run Code Online (Sandbox Code Playgroud)