我正在创建一个"气泡生成器"作为将在页面上运行的背景效果。发电机工作正常,但速度变慢了,过了一段时间就会出现批次。
演示:http://jsfiddle.net/Dud2q/
我将演示设置为以1毫秒的间隔运行,这样当你重新启动小提琴时,很容易看到速度减慢(尤其是当你将结果窗口设置得很大时)。
问题是,我有数千个对这个代码的调用(每个气泡一个):
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x+1, y+1);
ctx.stroke();
有人知道在画布上画一个像素的更快方法吗?
此外,如果有人想尝试让泡沫更逼真,我不会抱怨:)
与其一个接一个地绘制气泡,不如一次绘制呢?即将CCD_ 1和CCD_?它在Firefox上看起来要快得多。:)
$.extend(Number.prototype, {
times : function(cb){ for(var i=0; i<this; i++){ cb(i); }},
interval : function(cb){ return setInterval(cb, this); },
timeout : function(cb){ return setTimeout(cb, this); }
});
$(function(){
var $canvas = $('<canvas></canvas>'),
ctx = $canvas[0].getContext('2d'),
$cont = $('#fish-bubbles'),
generators = [],
bubbles = [],
w, h;
$cont.append($canvas);
$(window).bind('resize', onResize);
onResize();
5..times(createBubbleGenerator);
1..interval(drawBubbles);
function drawBubbles(){
ctx.clearRect(0, 0, w, h);
var newBubbles = [],
x, y, i, j, m, imgData, offset;
for(var i=0, l=generators.length; i<l; i++){
for(var j=0, m=0|Math.random()*6; j<m; j++){
newBubbles.push( 0|generators[i] + j );
}
generators[i] = Math.max(0, Math.min(w, generators[i] + Math.random()*10 - 5));
}
bubbles.unshift(newBubbles);
for(i=0; i<bubbles.length; i++){
y = h - i*2;
if(y<0){
bubbles.splice(i);
break;
}
ctx.beginPath();
for(j=0, m=bubbles[i].length; j<m; j++){
x = 0|(bubbles[i][j] += Math.random() * 6 - 3);
ctx.moveTo(x, y);
ctx.lineTo(x+1, y+1);
}
ctx.stroke();
}
}
function createBubbleGenerator(){
generators.push(0|Math.random() * w);
}
function onResize(){
w = $cont.width();
h = $cont.height();
$canvas.attr('width', w).attr('height', h);
ctx.strokeStyle = '#AAA';
}
});
然而,当泡沫更多时,它确实会放缓。
我猜您需要研究getImageData
和setImageData
方法。返回的图像数据可写入到像素级别。我想你可以用黑色填充画布,在画布上调用getImageData,更新下一帧气泡返回的像素数据,然后用setImageData将其写回画布。无休止地重复最后两个步骤,令人作呕。
请参阅此处了解更多详细信息。