【发布时间】:2018-06-01 09:47:09
【问题描述】:
下面的 sn-p 代码显示了一个名为“Circle”的函数对象被绘制到画布元素上。我知道如何从屏幕上删除圆的 visual 方面。我可以根据event.listener 或“对象碰撞”,使用c.globalAlpha=0.0; 随着时间的推移简单地改变它的不透明度,但是如果我在视觉上 undraw 说圆圈;它仍然存在并且正在计算,它仍然占用浏览器资源,因为它在我的画布元素上来回弹跳。
所以我的问题是:一旦实例化/绘制到画布上,删除/删除函数对象的最佳方法是什么? =>(这样它才能真正被删除并且不会在浏览器中无形地弹跳)
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;
}
<canvas id="myCanvas" width="200" height="60" style="background-color: white">
【问题讨论】:
-
你可以别再打电话给
circle.update();了吗? -
那么也许可以为更新函数设置一个条件?那么如果更新函数没有被调用:那么函数对象保持在上次成功更新后的最后一个位置?
-
只要停止引用它,它就会自动被垃圾回收 - 例如,如果它是 Circles 数组中的一个对象或其他要绘制的对象。
标签: javascript canvas