实例化/绘制到画布后删除/删除函数对象的最佳方法是什么?

时间:2018-05-31 23:53:56

标签: javascript canvas

下面的代码段显示了一个名为“Circle”的函数对象被绘制到canvas元素。我知道如何从屏幕上删除圆圈的 visual 方面。我可以根据if fd, err := io.Open("filename"); err != nil { if err != io.ErrFileNotFound { log.Fatalf("Error opening file: %s", err) } } 或“对象碰撞”使用c.globalAlpha=0.0;随时间改变其不透明度,但是如果我在视觉上 undraw 表示圈子;它仍然存在并被计算,它仍然占用浏览器资源,因为它在我的canvas元素上无形地反弹。

所以我的问题是:在实例化/绘制到画布后删除/删除函数对象的最佳方法是什么? =>(以便它真正被删除而不是无形中弹跳浏览器)

event.listener
let canvas = document.getElementById('myCanvas');
let c = canvas.getContext('2d');

function Circle(x, y, arc, dx, dy, radius){
  this.x = x;
  this.y = y;
  this.dx = dx;
  this.dy = dy;
  this.arc = arc;
  this.cCnt = 0;
  this.radius = radius;

  this.draw = function() {
    c.beginPath();
    //context.arc(x,y,r,sAngle,eAngle,counterclockwise);
    c.arc(this.x, this.y, this.radius, this.arc, Math.PI * 2, false); //
    c.globalAlpha=1;
    c.strokeStyle = 'pink';
    c.stroke();
  }

  this.update = function() {
    if (this.x + this.radius > canvas.width || this.x - this.radius < 0){
      this.dx = -this.dx;
    }
    if (this.y + this.radius > canvas.height || this.y - this.radius < 0){
      this.dy = -this.dy;
    }
    this.x += this.dx;
    this.y += this.dy;

    this.draw();
  }
}

var circle = new Circle(2, 2, 0, 1, 1, 2); // x, y, arc, xVel, yVel, radius

function animate() {
  requestAnimationFrame(animate);
  c.clearRect(0, 0, canvas.width, canvas.height)
  circle.update();
}

animate();
body {
      background-color: black;
      margin: 0;
    }

1 个答案:

答案 0 :(得分:1)

许多画布库通过保持画布场景中的对象数组来解决此问题。每次调用animate()函数时,它都会遍历对象列表并为每个函数调用update()(为了简单起见,我使用的是您使用的名称)。

这允许您通过在阵列中添加或删除对象来控制场景中的内容。从阵列中删除对象后,它们将不再更新(如果没有其他引用,则会收集垃圾)。

以下是一个例子:

const sceneObjects = [];

function animate() {
  requestAnimationFrame(animate);
  c.clearRect(0, 0, canvas.width, canvas.height);

  // Update every object in the scene
  sceneObjects.forEach(obj => obj.update());
}

// Elsewhere...

function foo() {
  // Remove an object
  sceneObjects.pop();

  // Add a different object
  sceneObjects.push(new Circle(2, 2, 0, 1, 1, 2));
}

通过创建一个SceneCanvas类/对象来保持场景对象列表并为程序的其他部分提供一个接口(用于例如,Scene.add(myNewCircle)Scene.remove(myOldCircle))。

相关问题