2 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
該過濾器適用于圖像數(shù)據(jù)ImageData
。圖像數(shù)據(jù)無法顯示,因此需要轉(zhuǎn)換為某種可顯示的形式,例如畫布。
您還需要從圖像中獲取圖像數(shù)據(jù)。標(biāo)準(zhǔn)圖像不允許訪問像素,因此您需要將圖像轉(zhuǎn)換為畫布以獲取像素。
請(qǐng)注意,不安全的圖像(跨域、本地文件存儲(chǔ))可能無法為您提供像素訪問權(quán)限。如果您在請(qǐng)求中提供正確的CORS標(biāo)頭并且服務(wù)器接受請(qǐng)求(如下例所示) ,一些跨域圖像將允許訪問。
例子
我已經(jīng)向 Filter 對(duì)象添加了一些輔助函數(shù),這些函數(shù)將復(fù)制、創(chuàng)建和從各種圖像源中獲取像素。
Filter
在示例中抽象了術(shù)語(yǔ)圖像。就示例而言,圖像是類似對(duì)象的圖像,可以是CSSImageValue
、HTMLImageElement
、SVGImageElement
、HTMLVideoElement
、HTMLCanvasElement
、ImageBitmap
或OffscreenCanvas
中的任何一個(gè)ImageData
。
const image = new Image;
image.src = "https://upload.wikimedia.org/wikipedia/commons/1/15/Late_model_Ford_Model_T.jpg";
image.crossOrigin = "Anonymous"; // CORS
image.addEventListener("load", () => applyFilter(image), {once: true});
const Filters = {
createImage(w, h) {
const can = document.createElement("canvas");
can.width = w;
can.height= h;
return can;
},
copyImage(img) {
const image = this.createImage(img.width, img.height);
const ctx = image.getContext("2d");
if (img instanceof ImageData) { ctx.putImageData(img, 0, 0) }
else { ctx.drawImage(img, 0, 0, img.width, img.height) }
return image;
},
getPixels(img) {
if (!(img instanceof HTMLCanvasElement)) { img = this.copyImage(img) }
const ctx = img.getContext("2d");
return ctx.getImageData(0, 0, img.width, img.height);
},
threshold(pixels, threshold, light = [255,255,255], dark = [0,0,0]) { // light, dark arrays of RGB
var d = pixels.data, i = 0, l = d.length;
while (l-- > 0) {
const v = d[i] * 0.2126 + d[i+1] * 0.7152 + d[i+2] * 0.0722;
[d[i], d[i+1], d[i+2]] = v >= threshold ? light : dark;
i += 4;
}
return pixels;
}
};
function applyFilter(image) {
const pixels = Filters.getPixels(image);
Filters.threshold(pixels, 100);
const thresholdImage = Filters.copyImage(pixels);
att.classList.remove("hide"); // Image can be seen so show attribution
document.body.appendChild(image); // add original to page
document.body.appendChild(thresholdImage); // add filtered to page
}
/* Image source
By Rmhermen - Transferred from en.wikipedia to Commons., CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=468996
*/
.hide {display: none}
div { font-size: x-small }
canvas { width: 46% }
img { width: 46% }
<div id="att" class="hide">By Rmhermen - Transferred from en.wikipedia to Commons., CC BY-SA 3.0, <a href="https://commons.wikimedia.org/w/index.php?curid=468996">image source</a></div>

TA貢獻(xiàn)1934條經(jīng)驗(yàn) 獲得超2個(gè)贊
如果你想在 HTML 上應(yīng)用這個(gè)過濾器<div>
,那么畫布解決方案不是最好的。
相反,對(duì)于簡(jiǎn)單的情況,請(qǐng)查看CSS 過濾器,對(duì)于更復(fù)雜的情況,請(qǐng)查看SVG 過濾器。
你想要的是一個(gè)簡(jiǎn)單的,只能用 CSS 過濾器來實(shí)現(xiàn):
#target {
background-image: url(https://i.stack.imgur.com/5Md7Z.jpg);
width: 600px;
height: 600px;
filter: brightness(115%) grayscale(100%) contrast(5000%);
}
<div id="target"></div>
添加回答
舉報(bào)