<!DOCTYPE html >
<html>
<head>
<meta charset="gb2312" />
<title>canvas 图片像素化-www.jb200.com</title>
<script type="text/
javascript">
function $$(id){
return document.getElementById(id);
}
function pageload(){
var cnv=$$("cnvMain");
var context=cnv.getContext("2d");
var image = new Image();
image.src = "example.jpg";
image.onload=function(){
context.drawImage(image, 0, 0, 500, 736);
var imageData = context.getImageData(0, 0, cnv.width, cnv.height);
var pixels = imageData.data;
var numPixels = pixels.length;
var numTileRows = 20;
var numTileCols = 20;
var tileWidth = imageData.width/numTileCols;
var tileHeight = imageData.height/numTileRows;
for (var r = 0; r < numTileRows; r++) {
for (var c = 0; c < numTileCols; c++) {
var x = (c*tileWidth)+(tileWidth/2);//圆心坐标
var y = (r*tileHeight)+(tileHeight/2);
// Use Math.floor to convert the pixel positions to integers
var pos = (Math.floor(y)*(imageData.width*4))+(Math.floor(x)*4);
var red = pixels[pos];
var green = pixels[pos+1];
var blue = pixels[pos+2];
var a=0.9;
context.fillStyle = "rgba("+red+", "+green+", "+blue+", "+a+")";
//正方形像素化
if(3<r&&r<7&&c>8&&c<15){
context.fillRect(x-(tileWidth/2), y-(tileHeight/2), tileWidth, tileHeight);
}
};
};
}
}
</script>
</head>
<body onload="pageload();">
<canvas id="cnvMain" width="500" height="736"> </canvas>
</body>
</html>