javascript - Is context.clearRect() really THAT expensive? -
i have piece of canvas animation exhibiting weird characteristics:
http://jsbin.com/olasol/2/edit
i'm on latest version of chrome. i'm using chrome's inbuilt fps monitor (you can activate going about:flags
). have marked line in javascript section think potential culprit:
fallingctx.clear();
this line nothing special. calls function in-turn calls clearrect()
.
the "weird" things notice are:
the
clear();
function causes noticeable fps drop on laptop (core 2 duo), not on desktop (i5 2500k).removing line alone sufficient produce 60fps on laptop well. expected, canvas doesn't clear after each frame, still, produces stable 60fps.
the fps drop happens when chrome window on larger side! when shrink window , reload, doesn't happen! (is more expensive clear larger rectangle?).
i tried replacing
clear()
drawimage()
of full white jpeg cover canvas. javascript able 200drawimage()
executions each cycle smaller image particles (evident second point). however, when add 1 singledrawimage
overall canvas, lags again! (make sure output occupies entire screen in order reproduce result.)
why happening? how fix it?
it really depends on hardware, think invocation of clearrect
has do! must zero-out piece of memory large enough handle canvas contents. can costly. think how memory has hold rgba @ hd resolutions... that's on 2 million pixels of data, around 8 mb in bytes admittedly, it's not that these days in general, if there's bandwidth or caching issues related pushing memory video card or doing 60 times second... well, expect problems.
what i've heard works clear around image formerly drawn. see http://jsbin.com/olasol/6/edit
i made following changes you.
(var i=0; i< noofdrops; ++i) { fallingctx.clearrect( fallingdrops[i].x-1, fallingdrops[i].y-1, fallingdrops[i].image.width+2, fallingdrops[i].image.height+2); } (var i=0; i< noofdrops; ++i) { fallingdrops[i].y += fallingdrops[i].speed; //set falling speed fallingctx.drawimage (fallingdrops[i].image, fallingdrops[i].x, fallingdrops[i].y); }
there's reason need clearrect
around image rendered simple reason escapes me. (it things being rendered not quite @ pixel specified... forget exactly).
you need fact starting render loop before image loaded (also in jsbin) added
var imgsource = "http://lorempixel.com/20/20/sports/"; var imgobj = new image();
and replaced superinit
function superinit() { imgobj.onload = function(){ flowerfallsetup(); requestanimframe(flowerfall); } imgobj.onerror = function (){ alert("could not load image"); } imgobj.src = imgsource; }
edit: i forgot mention because of prior image setup, did change line in flowerfallsetup
:
fallingdr["image"] = imgobj;
there many ways handle asynchronous loading of images, chose 1 easy example.
edit: have confess, there might bit more this. works fine on desktop browsers, on iphone, there are clipping issues. if can figure out what's causing problem i'll try post update.
Comments
Post a Comment