【问题标题】:Html5 Canvas overlayHtml5 画布覆盖
【发布时间】:2011-08-28 15:20:43
【问题描述】:

有没有一个好的解决方案可以用画布绘制带有叠加颜色的位图?

我要做的是为所有不透明的像素绘制一个具有唯一颜色的位图。 我没有找到任何解决方案,它可能对我有用!

谢谢

【问题讨论】:

标签: html canvas bitmap overlay


【解决方案1】:

Live Demo

一种方法是循环遍历每个像素并将 r/g/b 值更改为您想要的值。通过跳过 alpha 值,它只会将不透明像素更改为您想要的颜色。

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,255]; // 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]; // Green component
      pix[i+2] = uniqueColor[2]; // Blue component
      //pix[i+3] is the transparency.
}

ctx.putImageData(imgd, 0, 0);

// Just extra if you wanted to display within an img tag.
var savedImageData = document.getElementById("imageData");
savedImageData.src = canvas.toDataURL("image/png"); 

【讨论】:

  • 是的。我尝试了这种方法,但它对我的需要来说太小了。
  • @webshaker 太小是什么意思?以上只是使用了一个示例图像。
  • oups 太慢了抱歉。事实上,我会解释我想要做什么。我正在做一个编辑器。我希望能够在屏幕中选择一个精灵。我已经使用精灵的正方形进行了检测,但它不够准确。我喜欢将具有特定颜色的每个精灵绘制到隐藏缓冲区中,以便找到所选的确切精灵。
  • 啊,我明白了,是的,这种方法绝对是一种较慢的方法。
  • 是的 :) 但最终,阅读您的消息,我找到了一个很酷的解决方案。我首先检查矩形,然后将单击的像素读入精灵位图(取消 getImageData),如果它是透明的,我认为未选择精灵。我还没有完成,但它可能会解决我的问题。 :)
猜你喜欢
  • 2016-06-22
  • 2012-07-23
  • 2014-03-13
  • 2011-10-08
  • 2013-01-27
  • 1970-01-01
  • 2016-01-27
  • 1970-01-01
  • 2010-12-12
相关资源
最近更新 更多