700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > html5 图片局部马赛克 html5 canvas 图片打马赛克 demo

html5 图片局部马赛克 html5 canvas 图片打马赛克 demo

时间:2022-01-15 16:22:25

相关推荐

html5 图片局部马赛克 html5 canvas 图片打马赛克 demo

Canvas Mosaic

#pic{

display:none;

}

The size of the original pic need to be 360 pixs.

canvas 标签

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

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.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

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;

};

};

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。