您好,登錄后才能下訂單哦!
canvas中怎么實現(xiàn)圖片濾鏡效果,針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
1.獲取圖像數(shù)據(jù)
img.src = ’https://cache.yisu.com/upload/information/20210312/296/133192.jpg’;
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext(“2d”);
context.drawImage(img, 0, 0);
var canvasData = context.getImageData(0, 0, canvas.width, canvas.height);
2.設(shè)置過濾矩陣
var m_VideoType=0;
var pattern=new Array();
switch (m_VideoType)
{
case0://VIDEO_TYPE.VIDEO_STAGGERED:
{
pattern = [
0, 1,
0, 2,
1, 2,
1, 0,
2, 0,
2, 1,
];
break;
}
case1://VIDEO_TYPE.VIDEO_TRIPED:
{
pattern = [
0,
1,
2,
];
break;
}
case2://VIDEO_TYPE.VIDEO_3X3:
{
pattern =
[
0, 1, 2,
2, 0, 1,
1, 2, 0,
];
break;
}
default:
{
pattern =
[
0, 1, 2, 0, 0,
1, 1, 1, 2, 0,
0, 1, 2, 2, 2,
0, 0, 1, 2, 0,
0, 1, 1, 1, 2,
2, 0, 1, 2, 2,
0, 0, 0, 1, 2,
2, 0, 1, 1, 1,
2, 2, 0, 1, 2,
2, 0, 0, 0, 1,
1, 2, 0, 1, 1,
2, 2, 2, 0, 1,
1, 2, 0, 0, 0,
1, 1, 2, 0, 1,
1, 2, 2, 2, 0,
];
break;
}
}
var pattern_width = [ 2, 1, 3, 5 ];
var pattern_height = [6, 3, 3, 15 ];
3.獲取過濾數(shù)據(jù)
for ( var x = 0; x < canvasData.width; x++) {
for ( var y = 0; y < canvasData.height; y++) {
// Index of the pixel in the array
var idx = (x + y * canvasData.width) * 4;
var r = canvasData.data[idx + 0];
var g = canvasData.data[idx + 1];
var b = canvasData.data[idx + 2];
var nWidth = pattern_width[m_VideoType];
var nHeight = pattern_height[m_VideoType];
var index = nWidth * (y % nHeight) + (x % nWidth);
index = pattern[index];
if (index == 0)
var r = fclamp0255(2 * r);
if (index == 1)
var g = fclamp0255(2 * g);
if (index == 2)
var b = fclamp0255(2 * b);
// assign gray scale value
canvasData.data[idx + 0] = r; // Red channel
canvasData.data[idx + 1] = g; // Green channel
canvasData.data[idx + 2] = b; // Blue channel
canvasData.data[idx + 3] = 255; // Alpha channel
// 加上黑色的邊框
if(x < 8 || y < 8 || x > (canvasData.width - 8) || y > (canvasData.height - 8))
{
canvasData.data[idx + 0] = 0;
canvasData.data[idx + 1] = 0;
canvasData.data[idx + 2] = 0;
}
}
}
4.寫入過濾后的數(shù)據(jù)
context.putImageData(canvasData, 0, 0);
關(guān)于canvas中怎么實現(xiàn)圖片濾鏡效果問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。