I have created a function that adds "shadow" to the content of a canvas. The algorithm for adding shadow follows these rules:
- If the either
x
ory
is 0, ignore. - If the pixel on the current pixel's top left corner is not completely transparent, set current pixel's alpha value to 0.1.
This algorithm runs from top to bottom, left to right. Here's the relevant part, where rendered
is a canvas that already contain rendered content.
function getIndex(x, y){
return (y * width + x) * 4;
}
function isClear(x, y){
var index = getIndex(x, y);
return data[index + 3] === 0;
}
function isInShadow(x, y){
if(x < 1 || y < 1) return false;
if(isClear(x, y) && !isClear(x - 1, y - 1)) return true;
return false;
}
var width = rendered.width, height = rendered.height,
imgData = renderedCtx.getImageData(0, 0, width, height),
data = imgData.data;
for(var x = 0; x < width; x++){
for(var y = 0; y < height; y++){
if(isInShadow(x, y)){
data[getIndex(x, y) + 3] = 256 * 0.1;
}
}
}
renderedCtx.putImageData(imgData, 0, 0);
As you can see, this function performs per pixel manipulation and is quite slow in performance. What is a good way to improve performance, probably without checking each pixel independently?