阴影在计算上是昂贵的 - 缓存阴影
警告! 谨慎地涂抹阴影!
如果在动画循环中应用阴影,则应用阴影是昂贵的并且是倍增的。
相反,缓存图像(或其他图形)的阴影版本:
-
在应用程序开始时,在第二个仅限内存的 Canvas 中创建一个阴影版本的图像:
var memoryCanvas = document.createElement('canvas') ...
-
每当你需要阴影版本时,将预先阴影的图像从内存中的画布绘制到可见的画布:
context.drawImage(memoryCanvas,x,y)
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
canvas.style.border='1px solid red;';
document.body.appendChild(canvas);
// Always(!) use "img.onload" to give your image time to
// fully load before you try drawing it to the Canvas!
var img=new Image();
img.onload=start;
// Put your own img.src here
img.src="http://i.stack.imgur.com/hYFNe.png";
function start(){
ctx.drawImage(img,0,20);
var cached=cacheShadowedImage(img,'black',5,3,3);
for(var i=0;i<5;i++){
ctx.drawImage(cached,i*(img.width+10),80);
}
}
function cacheShadowedImage(img,shadowcolor,blur){
var c=document.createElement('canvas');
var cctx=c.getContext('2d');
c.width=img.width+blur*2+2;
c.height=img.height+blur*2+2;
cctx.shadowColor=shadowcolor;
cctx.shadowBlur=blur;
cctx.drawImage(img,blur+1,blur+1);
return(c);
}