2013年12月1日 星期日
HTML5 Canvas 馬賽克
<canvas id="myCanvas201312010546">不支援Canvas。</canvas>
</html>
<script type="text/javascript">
(function(){
var canvas,context,img = new Image(),imgDatas=[],frame=0;
var init = function(){
canvas = document.getElementById('myCanvas201312010546');
context = canvas.getContext('2d');
img.addEventListener('load' ,loadHandler , false);
//img.src = "images/dali.jpg";
img.src = '你圖片的所在路徑';
};
var loadHandler = function(e){
//console.log(canvas);
canvas.width = img.width;
canvas.height = img.height;
//context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
context.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
var pixels = imageData.data;
context.clearRect(0, 0, canvas.width, canvas.height);
//馬賽克磚塊數量
var numTileRows = 30;
var numTileCols = 30;
//每一塊馬賽克磚的長寬
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);
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];
//重新填滿色塊
context.fillStyle = "rgb("+red+", "+green+", "+blue+")";
context.fillRect(x-(tileWidth/2), y-(tileHeight/2), tileWidth, tileHeight);
};
};
};
init();
}());
</script>
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言