操作
在我的扩展中,我想操作一些图像。所以我尝试使用画布读取它们的原始像素。 问题是,如果在 chrome 代码中执行(img
是内容文档中的图像):
var src = document.createElement("canvas");
src.width = img.naturalWidth;
src.height = img.naturalHeight;
var srcCtx = src.getContext("2d");
在最后一行,它表示 getContext
不是函数。 另一方面,如果我运行(请注意第一行不同!):
var src = img.ownerDocument.createElement("canvas");
src.width = img.naturalWidth;
src.height = img.naturalHeight;
var srcCtx = src.getContext("2d");
srcCtx.drawImage(img, 0, 0);
var src_data = srcCtx.getImageData(0, 0, src.width, src.height);
不会返回错误,但 src_data 会显示为空。我想这可能与从 chrome 代码访问网页内容有关。有什么建议吗?
In my extension I'd like to manipulate some images. So I'm trying to read their raw pixels using canvas.
The problem is that if, in chrome code, I execute (img
is an image in a content document):
var src = document.createElement("canvas");
src.width = img.naturalWidth;
src.height = img.naturalHeight;
var srcCtx = src.getContext("2d");
on the last line it says that getContext
is not a function.
On the other hand if I run (notice that the first line is different!):
var src = img.ownerDocument.createElement("canvas");
src.width = img.naturalWidth;
src.height = img.naturalHeight;
var srcCtx = src.getContext("2d");
srcCtx.drawImage(img, 0, 0);
var src_data = srcCtx.getImageData(0, 0, src.width, src.height);
no error is returned, but src_data
comes out empty. I suppose it may have something to do with accessing web content from chrome code. Any suggestion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我怀疑第一个片段的问题是
document
是一个 XUL 文档,因此它的createElement
函数将创建一个 XUL 元素,并且不存在 XUL:canvas 这样的东西。可以在 XUL 文档中创建 HTML 元素,但是您需要使用 createElementNS()。更清楚地说,代码看起来像为什么
src_data
结果是空的,我不知道。I suspect the problem with the first snippet is that
document
is a XUL document, so itscreateElement
function will create a XUL element and there is no such thing as a XUL:canvas. It is possible to create HTML elements in a XUL document, but then you'll want to use createElementNS(). To be more clear the code would look likeWhy
src_data
comes out empty though, I don't know.正如我上面所说,问题出在另一段代码中。
这实际上是因为我误读了文档并认为 src_data 应该包含像素,而它应该是 src_data.data 。由于某种原因,我无法理解打印
uneval(src_data)
会返回({})
,而其中应该有三个成员,data
、宽度
和高度
。As I said above, the problem was in a different piece of code.
It was actually due to the fact that I misread the documentation and thought that
src_data
was supposed to contain the pixels, whereas it should have beensrc_data.data
. For some reason that I can't understand printing outuneval(src_data)
would return({})
instead, whereas in it there should be three members,data
,width
andheight
.我认为你应该使用
I think you should use