我一直在尝试将简单对比度和红色通道操作草图转换为p5.js.将像素操作从processig转换为p5.js时出错
原来.pde效果很好用processing.js:
// Declaring a variable of type PImage
PImage img;
void setup() {
size(564, 698);
// Make a new instance of a PImage by loading an image file
img = loadImage("../image.jpg");
}
void draw() {
loadPixels();
// We must also call loadPixels() on the PImage since we are going to read its pixels. img.loadPixels();
for (int x = 0; x < img.width; x++) {
for (int y = 0; y < img.height; y++) {
// Calculate the 1D pixel location
int loc = x + y*img.width;
// Get the R,G,B values from image
float r = red (img.pixels[loc]);
float g = green (img.pixels[loc]);
float b = blue (img.pixels[loc]);
// We calculate a multiplier ranging from 0.0 to 8.0 based on mouseX position.
// That multiplier changes the RGB value of each pixel.
float adjustBrightness = ((float) mouseX/width) * 4.0;
float adjustRed = ((float) mouseY/height) * 2.0;
r *= adjustBrightness; // see https://processing.org/reference/multiplyassign.html
g *= adjustBrightness;
b *= adjustBrightness;
r *= adjustRed;
// The RGB values are constrained between 0 and 255 before being set as a new color.
r = constrain(r,0,255);
g = constrain(g,0,255);
b = constrain(b,0,255);
// Make a new color and set pixel in the window
color c = color(r,g,b);
pixels[loc] = c;
}
}
updatePixels();
}
然而,转化为p5.js更新脚本(下同)时返回一个错误:
Error: Needs p5.Color or pixel array as argument.
我对于我尝试过的东西留下了一些评论: var img; // var sensitivity;
function preload() {
img = loadImage("../image.jpg");
}
function setup() {
createCanvas(564, 698);
pixelDensity(1);
img.loadPixels();
loadPixels();
}
function draw() {
loadPixels();
for (var x = 0; x < img.width; x++) {
for (var y = 0; y < img.height; y++) {
// Calculate the 1D location from a 2D grid
var loc = (x + y*img.width)*4;
// Get the R,G,B values from image
var r,g,b;
r = red (img.pixels[loc]);
g = green (img.pixels[loc]);
b = blue (img.pixels[loc]);
// Calculate an amount to change brightness based on proximity to the mouse
// var maxdist = 50;
// var d = dist(x, y, mouseX, mouseY);
var adjustBrightness = (mouseX/width)*4;
var adjustRed = (mouseY/height)*4;
r *= adjustBrightness;
g *= adjustBrightness;
b *= adjustBrightness;
r *= adjustRed;
// Constrain RGB to make sure they are within 0-255 color range
r = constrain(r, 0, 255);
g = constrain(g, 0, 255);
b = constrain(b, 0, 255);
// Make a new color and set pixel in the window
//color c = color(r, g, b);
// var pixloc = (y*width + x)*4;
c = color(r,g,b);
pixels[loc] = c;
// pixels[loc] = r; //red
// pixels[loc+1] = 40; //green
// pixels[loc+2] = b; //blue
// pixels[loc+3] = 50; //alpha
}
}
updatePixels();
}
我认为问题可能出现在red()green()blue()函数中。
您是否真的将原始代码作为JavaScript运行?或者你只是从Processing编辑器将它作为Java运行? –
是的,我在同一个apache2.4服务器上将.pde运行与processing.js和p5.js脚本进行了比较。处理代码的运行速度要快得多(可能是更新速率的两倍) – FGiorlando