0

现在重新发布问题更清楚了。

我所拥有的是一个页面,上面有 x 个图像。我想要做的是能够单击任何图像的任何部分,并使单击的图像中的特定颜色透明。Turning its Alpha to 0

所以,图像:

<div id="resizeImg" style="width:300px; left:50px;" class="pic">
    <img id="image" src="http://myurl.com/images/3727.jpg" width=300 />
</div>
<div id="resizeImg" style="width:300px; left:50px;" class="pic">
    <img id="image1" src="http://myurl.com/images/3728.jpg" width=300 />
</div>
<div id="resizeImg" style="width:300px; left:50px;" class="pic">
    <img id="image2" src="http://myurl.com/images/3729.jpg" width=300 />
</div>

以下是我正在尝试的,检查员告诉我ImageData { width=300, height=300, data=Uint8ClampedArray}

当我单击data=Uint8ClampedArray查看其中的内容时,浏览器 (ff) 冻结并询问是否要停止脚本。

所以它陷入了一个循环,当我最终看到时,data=Uint8ClampedArray it shows 0=255, 1=255, 2=255即使我点击了红色的东西。

我认为问题在于捕获鼠标位置和点击的像素。

// get mouse position

function findPos(obj) {
    var current_left = 0,
        current_top = 0;
    if (obj.offsetParent) {
        do {
            current_left += obj.offsetLeft;
            current_top += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return {
            x: current_left,
            y: current_top
        };
    }
    return undefined;
}

// click
$('[id^=image]').click(function (e) {
    var after = $(this)[0];
    after.src = white2transparent(after);
})

function white2transparent(img) {
    var c = document.createElement('canvas');
    var w = img.width,
        h = img.height;

    c.width = w;
    c.height = h;

    // get the position
    var position = findPos(img);
    var x = img.pageX - position.x;
    var y = img.pageY - position.y;
    var coordinate = "x=" + x + ", y=" + y;

    var ctx = c.getContext('2d');

    ctx.width = w;
    ctx.height = h;
    ctx.drawImage(img, 0, 0, w, h);
    var imageData = ctx.getImageData(0, 0, w, h);

    // show rgb colors in inspector
    console.log(imageData);

    var pixel = imageData.data;

    var r = 0,
        g = 1,
        b = 2,
        a = 3;
    for (var p = 0; p < pixel.length; p += 4) {
        if (
        // this is where I need to return the RGB found and replace 220
        pixel[p + r] >= 220 &&
            pixel[p + g] >= 220 &&
            pixel[p + b] >= 220) {
            pixel[p + a] = 0;
        }
    }

    ctx.putImageData(imageData, 0, 0);

    return c.toDataURL('image/png');
}

这部分是我需要返回 clickde 像素的 RGB 并将 220 替换为每个值的地方

if (
    // this is where I need to return the RGB found and replace 220
      pixel[p+r] >= 220 &&
      pixel[p+g] >= 220 &&
      pixel[p+b] >= 220)

编辑

当我尝试使用检查器查看坐标时:

// show x + y
console.log("x=" + x + ", y=" + y);

它返回x=NaN, y=NaN

4

1 回答 1

0

如果你想找到鼠标相对于图像的位置,你应该像这样使用点击事件本身

$('[id^=image]').click(function (e) {
   // an array representing the relative x\y mouse coordinates within the image
   var relativeMousePosition=[e.pageX-$(this).offset().left,e.pageY-$(this).offset().top];

})
于 2013-03-29T13:50:01.800 回答