javascript - 如何根据图像垂直条设置像素RGB值? (JavaScript)

标签 javascript image

我有一个 140 x 210 px 的图像,我试图将其分成三个相等的垂直条纹,如下所示:我需要将左侧垂直三分之一的所有像素的红色更改为 255,将所有像素的绿色更改为中间垂直方向的像素为 255,右侧垂直方向的所有像素的蓝色为 255。这应该具有的光学效果是在图像上创建垂直的红色、绿色和蓝色彩虹。

我尝试使用以下代码来执行此操作:

var image = new SimpleImage("hilton.jpg");
for (var p of image.values()) {
    if (p.getX() < 46) {
        p.setRed(255);
    }
    if (46 < p.getX() < 92) {
        p.setGreen(255);
    }
    if (p.getX() > 92) {
        p.setBlue(255);
    }
}

print(image);

它将红色和蓝色 strip 分别添加到图像的左侧和右侧。但是当我尝试在中间添加绿色条时,它会弄乱整个图像,即图像中的其他像素也会变成绿色。

如果可能的话,我想在没有任何库的情况下完成此操作。

最佳答案

您的代码有一个小问题:

if (46 < p.getX() < 92) {

是无效语法。应该是:

if (46 < p.getX() && p.getX() < 92) {
<小时/>

也就是说,如果不使用库,您只能使用 Canvas 来执行此操作,而不能仅更改图像上的像素:

// Setup
var canvas = document.getElementById("canvas"),
    ctx= canvas.getContext("2d"),
    img = new Image(),
    w = canvas.width / 3;

// Load image
img.crossOrigin = "anonymous";
img.src = 'http://i190.photobucket.com/albums/z257/americanwildlife/Mammal/Z-ucumari-Valerie-redwolf.jpg';

// When the image has loaded
img.onload = function(){
    // Draw it and get it's data
    ctx.drawImage(img, 0, 0);
    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height),
        data = imgData.data;

    // Iterate over all the pixels
    for (var i = 0; i < data.length; i += 4) {
        // The current pixels' x position
        var x = Math.floor(i / 4) % canvas.width;

        //Set the pixels' r, g, b channels if x is within certain bounds.
        if(x < w)
            data[i] = 255;   // Red
        else if(x >= w && x < w * 2)
            data[i+1] = 255; // Green
        else
            data[i+2] = 255; // Blue
    }

    // Re-draw the image.
    ctx.putImageData(imgData, 0, 0);
}
<canvas id="canvas" width="800px" height="639px"></canvas>

关于javascript - 如何根据图像垂直条设置像素RGB值? (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32693700/

相关文章:

javascript - 通过 src 删除图像

javascript - 提交表单数据到Highcharts addPoint方法动态更新表单

javascript - 在 Javascript(或 Node)中,如何识别函数的参数?

Javascript 存储数据

javascript - 使用 Colorbox(JQuery 灯箱插件),如何单击图像关闭灯箱?

CSS背景100%高度问题

php - Sympfony2 使用文件系统按名称或路径删除文件

PHP 显示缩小和调整大小的图像

javascript - "Show More"div 内按钮的链接(多个显示更多按钮)

javascript - 访问其定义中的数组项,相对索引