【问题标题】:Editing an image without creating a new one编辑图像而不创建新图像
【发布时间】:2016-07-31 07:46:25
【问题描述】:
我正在尝试使用 JavaScript 编辑图像(img 元素),但 google 仅向我提供有关如何创建具有所需更改的新图像的信息。
出于性能原因,我希望能够在不创建新图像的情况下编辑现有图像 - 这完全可以通过浏览器环境中的 JavaScript 实现吗?
我想要完成的是即时编辑 three.js 模型的相当大的 uv 贴图,而无需不断地重新创建整个图像(性能问题)。
【问题讨论】:
标签:
javascript
image
canvas
three.js
【解决方案1】:
有一个很酷的图片库:p5.js
我不确定它是否能够直接修改使用 HTML 创建的 img 元素,但如果使用 JS 加载图像对您来说没有问题,那么它就可以了。
Here如何修改像素亮度的示例:
var img;
function preload() {
img = loadImage("image.png");
}
function setup() {
createCanvas(720, 200);
img.loadPixels();
loadPixels();
}
function draw() {
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 = 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 = 255*(maxdist-d)/maxdist;
r += adjustbrightness;
// Constrain RGB to make sure they are within 0-255 color range
r = constrain(r, 0, 255);
// Make a new color and set pixel in the window
//color c = color(r, g, b);
var pixloc = (y*width + x)*4;
pixels[pixloc] = r;
pixels[pixloc+1] = r;
pixels[pixloc+2] = r;
pixels[pixloc+3] = 255;
}
}
updatePixels();
}