p5.Image filter() 方法
JavaScript p5.js库中p5.Image的filter()方法用于对图像应用过滤器。 p5.js中预定义了几个预设,可以使用不同的强度级别来获得所需的效果。
句法:
filter( filterType, filterParam )
参数:此函数接受两个参数,如上所述和如下所述。
- filterType:它是一个常量,定义了要用作过滤器的预设。它的值可以是 THRESHOLD、GRAY、OPAQUE、INVERT、POSTERIZE、BLUR、ERODE、DILATE 或 BLUR。
- filterParam:它是每个过滤器唯一的数字,会影响过滤器的功能。它是一个可选参数。
注意:以下示例中使用的 JavaScript 库如下所示。这些用于任何 HTML 文件的 head 部分。本文底部给出了下载参考链接。
示例 1:下面的示例说明了p5.js中的filter()方法。
javascript
function preload() {
img_orig =
loadImage("sample-image.png");
img_filter =
loadImage("sample-image.png");
}
function setup() {
createCanvas(500, 400);
textSize(20);
// Draw the original image
text("Click on the button to " +
"add a filter to the image", 20, 20);
text("Original Image:", 20, 60);
image(img_orig, 20, 80, 200, 100);
// Apply the GRAYSCALE filter
img_filter.filter(GRAY);
// Draw the image with filter
text("Filter Image:", 20, 220);
image(img_filter, 20, 240, 200, 100);
}
javascript
function preload() {
img_orig =
loadImage("sample-image.png");
img_filter =
loadImage("sample-image.png");
}
function setup() {
createCanvas(500, 400);
textSize(20);
btnBlur = createButton("Add Blur filter");
btnBlur.position(30, 360);
btnBlur.mousePressed(applyBlur);
btnInvert = createButton("Add Invert filter");
btnInvert.position(160, 360);
btnInvert.mousePressed(applyInvert);
}
function draw() {
clear();
text("Click on the button to add a " +
"filter to the image", 20, 20);
text("Original Image:", 20, 60);
image(img_orig, 20, 80, 200, 100);
text("Filter Image:", 20, 220);
image(img_filter, 20, 240, 200, 100);
}
function applyBlur() {
// Add the BLUR filter to the image
img_filter.filter(BLUR, 10);
}
function applyInvert() {
// Add the INVERT filter to the image
img_filter.filter(INVERT);
}
输出:
示例 2:
javascript
function preload() {
img_orig =
loadImage("sample-image.png");
img_filter =
loadImage("sample-image.png");
}
function setup() {
createCanvas(500, 400);
textSize(20);
btnBlur = createButton("Add Blur filter");
btnBlur.position(30, 360);
btnBlur.mousePressed(applyBlur);
btnInvert = createButton("Add Invert filter");
btnInvert.position(160, 360);
btnInvert.mousePressed(applyInvert);
}
function draw() {
clear();
text("Click on the button to add a " +
"filter to the image", 20, 20);
text("Original Image:", 20, 60);
image(img_orig, 20, 80, 200, 100);
text("Filter Image:", 20, 220);
image(img_filter, 20, 240, 200, 100);
}
function applyBlur() {
// Add the BLUR filter to the image
img_filter.filter(BLUR, 10);
}
function applyInvert() {
// Add the INVERT filter to the image
img_filter.filter(INVERT);
}
输出:
在线编辑器: https://editor.p5js.org/
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5.Image/filter