[英]Canvas, moving objects, clearRect in javascript
基本上,我的问题是我无法理解为什么我在代码中使用的函数clearRect
不能清理矩形(为了移动它们,我使用了setinterval
函数)。 我有正在移动的矩形。
在Set Interval函数中,您可以看到context.clearRect(0, 0, context.elem.width, context.elem.height);
我试图将其放在循环之前(没有用)和循环中(相同的:()。可以解决此问题吗?
window.onload = function () {
function Shape(x, y, w, h, fill) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.fill = fill;
}
// get canvas element.
var elem = document.getElementById('paper');
context = elem.getContext('2d');
//var container = {x:100, y:100, width:1200, height: 800};
context.fillStyle = "black";
context.fillRect(0, 0, elem.width, elem.height);
// check if context exist
if (elem.getContext) {
var array = [];
array.push(new Shape(20, 0, 50, 50, "red"));
array.push(new Shape(20, 60, 50, 50, "red"));
array.push(new Shape(20, 120, 50, 50, "red"));
array.push(new Shape(80, 0, 50, 50, "red"));
array.push(new Shape(80, 60, 50, 50, "red"));
array.push(new Shape(80, 120, 50, 50, "red"));
array.push(new Shape(140, 0, 50, 50, "red"));
array.push(new Shape(140, 60, 50, 50, "red"));
array.push(new Shape(140, 120, 50, 50, "red"));
//context = elem.getContext('2d');
}
//function draw (){
// context.fillStyle = 'red';
//context.fillRect(container.x, container.y, container.width, container,height);
//}
setInterval(function () {
/// clear canvas for each frame
//context.clearRect(0, 0, context.elem.width, context.elem.height);
/// iterate object array and move all objects
for (var i = 0, oRec; oRec = array[i]; i++) {
// context.clearRect(0, 0, context.elem.width, context.elem.height);
oRec.x++; /// update each object's position
context.beginPath();
context.fillStyle = oRec.fill;
context.fillRect(oRec.x, oRec.y, oRec.w, oRec.h);
context.fill();
}
}, 40);
};
尝试使用此方法,因为上下文没有elem
属性:
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
或直接使用elem
(速度更快,编写时间也更短):
context.clearRect(0, 0, elem.width, elem.height);
clearRect()
清除画布上的所有内容 ,包括填充的背景(默认情况下,画布元素是透明的,将处于初始状态或使用clearRect()
时再次变为画布状态)。
任一取代clearRect()
与fillRect()
使用黑色fillStyle
或设置为元素的CSS背景(后者将不会与任何图像一起保存,如果所需要的,即。 toDataURL()
黑色背景:
您可以通过仅清除框来进一步优化fillRect()
(因为它比clearRect()
慢clearRect()
(请记住在每侧为反走样像素添加一个像素)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.