Использование холста для применения фильтров
фильтра свойство
Хотя хром и светлячок и поддерживает ctx.filter
свойства, они требуют настроек браузера флагов для активации. После активации свойство фильтра 2d Context использует синтаксис фильтра CSS и применяет фильтр ко всем вызовам рендеринга. ref MDN CanvasRenderingContext2D.filter
ctx.filter = "blur(5px)"; // only applies to proceeding rendering calls existing
// current pixels remain unchanged
ctx.drawImage(image,0,0); // draw an image blurred 5px
Добавить фильтр в изображение. Только работает с Chrome и FIrefox с установленными соответствующими флагами браузера.
// assume image is a loaded image
var filteredImage = document.createElement("canvas");
var ctx = filteredImage.getContext('2d');
filteredImage.width = image.width;
filteredImage.height = image.height;
ctx.filter = "blur(10px) grayscale(100%)";
ctx.drawImage(image, 0, 0); // draw the image applying the filter
ctx.filter = ""; // turn off the filter as no needed any more
// You can now save the image filteredImage by using
ctx.toDataURL("image/jpeg",0.75);
Простейшее решение
Если вам нужна полная поддержка браузера вы должны будете найти библиотеку Javascript фильтра, есть много, чтобы выбрать из, хотя я не одобрит ни один из них.
Написать своя
Альтернативы писать свои собственные фильтры, (отличная возможность обучения) большинство фильтров являются очень простыми функциями манипулирования пикселей и Существует много информации о том, как работе различных фильтров. Чтобы узнать больше о 2D API MDN CanvasRenderingContext2D и быстрый грунтовки на сверток фильтры Image Filters with Canvas
Например, оттенки серого фильтра (самый основной свертки фильтров взвешенную сумму красного, зеленого и синего каналов преобразуется в шкале серого)
const PERS_R = 0.2; // approx human perceptual frequency/intensity response for r,g,b popular in the CG world and based on Manhattan 0.2126, 0.7152, 0.0722
const PERS_G = 0.7; // for red green and blue
const PERS_B = 0.1;
function applyGreyScale(image, percent, perc){ // 0 <percent>= 100
if(image === null || image === undefined){
throw new ReferenceError("applyGreyScale argument image is undefined or null");
}
const p = percent === undefined ? 1: percent/100;
const rp = 1-p; // reciprocal of p
perc = 1 - (perc === undefined ? 0 : Math.min(1, Math.max(0,perc))); // clamp if defined
var filteredImage = document.createElement("canvas");
var ctx = filteredImage.getContext('2d');
const w = filteredImage.width = image.width;
const h = filteredImage.height = image.height;
ctx.drawImage(image, 0, 0); // draw the image
var imageData = ctx.getImageData(0, 0, w ,h); // get the pixel data
var dat = imageData.data; // reference the pixel data
var ind = (w * h * 4) - 4; // pixel data array index point to last pixel each pixel is 4 bytes RGBA
const mean = 1/3; // mean contribution of each channel to gray
const pr = PERS_R + perc * (mean - PERS_R);
const pg = PERS_G - perc * (PERS_G- mean);
const pb = PERS_B + perc * (mean - PERS_B);
var grey;
while(ind >= 0){ // do for all pixels
grey = dat[ind] * pr; // get gray by adding each channel's contribution
grey += dat[ind + 1] * pg;
grey += dat[ind + 2] * pb;
dat[ind] = rp * dat[ind] + p * grey; // mix the grey with the existing colour
dat[ind + 1] = rp * dat[ind + 1] + p * grey; // mix the grey with the existing colour
dat[ind + 2] = rp * dat[ind + 2] + p * grey; // mix the grey with the existing colour
ind -= 4;
}
ctx.putImageData(imageData,0,0); // put the new pixels back on the image
filteredImage.ctx = ctx; // Add 2D context for later use
return filteredImage; // return the filtered image
}
/*
To use applyGreyScale(image [, percent [, perc]]) where percent and perc are optional
image is the image to get a gray scale from
percent is the amount of gray to apply 0 is none 100 is full. Default 100
perc is the amount of the perception curve applied to the grey. 0 no perception adjustment, 1 is full perceptual adjustment. Default is 1
Returns image with ctx property added for access to 2D interface
*/
и относительно проста в использовании
// convert image to greyscaled image
var dataURL = applyGreyScale(image).ctx.toDataURL("image/jpeg",0.75);
Здравствуйте, спасибо за ответ. Я пытаюсь манипулировать с помощью фильтров imageData.style ["filter"] = "grayValue (0.5)"/ctx.style ["filte"] = "grayValue (0.5)", но код, похоже, не работает. Любые входы на одном и том же? – user2814819
Вы не можете использовать стиль 'filter' по стилю. Вы должны использовать его непосредственно 'ctx.filter'. См. Ответ @ Blindman67. –