【问题标题】:Making white pixels in canvas transparent?使画布中的白色像素透明?
【发布时间】:2012-03-07 03:14:54
【问题描述】:

我试图创建一个更改图像颜色的脚本,我找到了一种更改颜色的方法,但是由于图像具有白色背景,它会改变所有图像,是否可以以某种方式忽略白色像素?

这是目前为止的代码:

    <!doctype html>
<html>
<head>

</head>

<body>
<h4>Original Image</h4>
<img id="testImage" src='../src/test.png'/>

<h4>Image copied to canvas</h4>
<canvas id="canvas" width="500" height="500"></canvas>

<h4>Modified Image copied to an image tag</h4>
<img id="imageData"/>

<script>

var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
image = document.getElementById("testImage");

ctx.drawImage(image,0,0);

var imgd = ctx.getImageData(0, 0, 128, 128),
    pix = imgd.data,
    uniqueColor = [0,0,150]; // Blue for an example, can change this value to be anything.

// Loops through all of the pixels and modifies the components.
for (var i = 0, n = pix.length; i <n; i += 4) {
      pix[i] = uniqueColor[0];   // Red component
      pix[i+1] = uniqueColor[1]; // Blue component
      pix[i+2] = uniqueColor[2]; // Green component
      //pix[i+3] is the transparency.
}

ctx.putImageData(imgd, 0, 0);


var savedImageData = document.getElementById("imageData");
savedImageData.src = canvas.toDataURL("image/png");
</script>
</body>
</html>

【问题讨论】:

  • 您将要使用@aglassman 的答案。但是为您的图像制作一个画布元素并在启动时对其进行处理。然后将画布元素绘制到画布上。这将显着提高性能。

标签: javascript html canvas


【解决方案1】:

这样的东西对你有用吗?

    if (pix[i] == 255 &&  
        pix[i+1] == 255 &&
        pix[i+2] == 255)
    {
    //pixel is white
    }
    else
    {
    //pixel is not white, modify it.
    }

【讨论】:

  • 我试图让它工作,但似乎没有成功(我可能放错了我不是专家)我将如何放置那段代码?
  • 很抱歉现在用你的代码做了,它可以工作。你太棒了,谢谢。
  • 它适用于某些图像,而另一些则不适用,很奇怪。当我从网络上获取图像时似乎不起作用。
  • 这很奇怪。我会为 firefox 尝试 firbug,并在失败的图像上调试你的 JavaScript。那应该查明故障点。祝你好运!
  • 我真的不知道如何使用 firebugs 调试器,使用 google chrome 我得到 SECURITY_ERR: DOM Exception 18 between: var imgd = ctx.getImageData(0, 0, 250, 250), (错误在这里) pix = imgd.data,搜索了一些,他们说这可能是因为我通过 c:// 而不是 localhost 访问该站点,但我没有。试图解决它,但找不到问题。
猜你喜欢
  • 1970-01-01
  • 2021-03-29
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
  • 2012-01-13
  • 2010-10-20
相关资源
最近更新 更多