重绘后画布不清除

时间:2014-05-30 11:18:02

标签: html5 canvas dart

我使用Canvas在Dart制作了一个动画。圆圈在屏幕上以50 px / s的角度对角移动。但是,调用clearRect方法时画布不会清除。任何人都可以说出原因吗?

I looked at another answer但这没有帮助。

HTML:

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <title>ForceTest</title>
    <link rel="stylesheet" href="forcetest.css">
  </head>
  <body>

    <canvas id="stage" width=500 height=500></canvas>

    <script type="application/dart" src="forcetest.dart"></script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>

forcetest.dart:

import 'dart:html';
import 'dart:math';
import 'package:vector_math/vector_math.dart';


List<ICanvasObject> objects = new List<ICanvasObject>();
CanvasElement canvas = querySelector('#stage');
CanvasRenderingContext2D ctx = canvas.getContext('2d');

void main() {
  objects.add(new Particle(100.0, 100.0));

  window.requestAnimationFrame(update);

}

class Particle implements ICanvasObject, IPhysicsObject {

  double _sx;
  double _sy;
  Vector2 _s;
  double _vx = 0.0;
  Vector2 _v = new Vector2(50.0, 50.0);

  Particle(double x, double y) {
    _sx = x;
    _sy = y;
    _s = new Vector2(x, y);
  }

  void draw(CanvasRenderingContext2D ctx) {
    ctx.arc(_s.x, _s.y, 10, 0, 2*PI);
    ctx.fill();
  }

  void recalculate() {
    _s.addScaled(_v, 1/60);
  }

}

abstract class ICanvasObject {
  void draw(CanvasRenderingContext2D ctx);
}

abstract class IPhysicsObject {
  void recalculate();
}

void update(num time) {

  for (IPhysicsObject object in objects.where((i) => 
        i is IPhysicsObject
      ).toList()) object.recalculate();


  ctx.clearRect(0, 0, 500, 500);
  for (ICanvasObject object in objects) object.draw(ctx);
  window.requestAnimationFrame(update);
}

1 个答案:

答案 0 :(得分:4)

您的方法中需要beginPath()

void draw(CanvasRenderingContext2D ctx) {
    ctx.beginPath();  // reset path
    ctx.arc(_s.x, _s.y, 10, 0, 2*PI);
    ctx.fill();
}

如果您没有当前路径将累积所有这些弧线,并且在调用fill()时,新的将与所有旧弧一起填充,使其看起来像帆布未被清除。