<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Canvas Mosaic</title>
<style>
#pic{
display:none;
}
</style>
</head>
<body>
The size of the original pic need to be 360 pixs.<br/>
<img id="pic" src="star.jpg" width="360" height="360"/><br/><br/>
canvas 标签<br/>
<canvas id="myCanvas" width="360" height="800"></canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("pic");
img.onload = function(){
ctx.drawImage(img,0,0);
var picSize = 360;
var currentX = 0;
var currentY = 0;
while(currentY<picSize && currentX<picSize){
var imageData = ctx.getImageData(currentX,currentY,20,20);
// need to run on server due to the using getImageDta
var rgbaArray =caculateRGBA(imageData);
var newImageData = ctx.createImageData(imageData);
for (var i = 0; i <newImageData.width*newImageData.height*4; i+=4){
newImageData.data[i+0]=rgbaArray[0];
newImageData.data[i+1]=rgbaArray[1];
newImageData.data[i+2]=rgbaArray[2];
newImageData.data[i+3]=rgbaArray[3];
};
ctx.putImageData(newImageData,currentX,currentY+400);
currentX+=20;
if(currentX>=picSize){
currentX=0;
currentY+=20;
};
}
function caculateRGBA(imgData){
var RGBA = [0,0,0,255];
//caculate avg rgb
var sumR = 0;
var sumG = 0;
var sumB = 0;
var sumA = 0;
var pixNum = imgData.width*imgData.height;
//console.log("area width: " + imgData.width + " pixs.");
//console.log("area heitht: " + imgData.height + " pixs.");
//console.log("Total pix number: " + pixNum);
for (var i = 0; i <imgData.width*imgData.height*4; i+=4) {
sumR += imgData.data[i+0];
sumG += imgData.data[i+1];
sumB += imgData.data[i+2];
sumA += imgData.data[i+3];
};
var avgR = Math.round(sumR/pixNum);
var avgG = Math.round(sumG/pixNum);
var avgB = Math.round(sumB/pixNum);
var avgA = Math.round(sumA/pixNum);
/*
console.log("R:"+avgR);
console.log("G:"+avgG);
console.log("B:"+avgB);
console.log("A:"+avgA);
*/
RGBA[0] = avgR;
RGBA[1] = avgG;
RGBA[2] = avgB;
RGBA[3] = avgA;
console.log(RGBA);
return RGBA;
};
};
</script>
</body>
</html>