HTML5 canvas 图像缓存/putImageData 问题

发布于 2024-10-20 06:56:29 字数 533 浏览 1 评论 0原文

我使用 HTML5 画布加载图像的单个实例,然后将其多次传输到单个画布上。该图像需要一些轻微的基于像素的操作才能对其进行自定义。我最初的攻击计划是加载图像,将其传输到背景画布,在其上绘制我的修改,然后获取图像数据并将其缓存以供将来使用。

以下是我为此目的编写的一些代码:

context.drawImage(img, 0, 0);
context.fillStyle = '#ffffff';
context.fillRect(0, 0, 2, 2);  // Draw a 2x2 rectangle of white pixels on the top left of the image

imageData = context.getImageData(0, 0, img.width, img.height);
cusomImage = imageData;

虽然这有效,但我注意到我的图像(透明的 PNG)不保持透明度。相反,当使用 putImageData 将其放置到我的正面画布上时,它会以黑色背景渲染。如何保持透明度?

欢迎任何建议!

I'm using the HTML5 canvas to load a single instance of an image which I then blit multiple times onto a single canvas. The image needs some slight pixel-based manipulation in order to customise it. My initial plan of attack had been to load the image, blit it to a backing canvas, draw my modifications on-top of it, and then grab the image data and cache it for future use.

Here's some code I've written to that effect:

context.drawImage(img, 0, 0);
context.fillStyle = '#ffffff';
context.fillRect(0, 0, 2, 2);  // Draw a 2x2 rectangle of white pixels on the top left of the image

imageData = context.getImageData(0, 0, img.width, img.height);
cusomImage = imageData;

While this works, I've noticed that my image (which is a transparent PNG) does not maintain transparency. Instead, when using putImageData to place it onto my front-facing canvas, it is rendered with a black background. How do I maintain transparency?

Any suggestions are welcome!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

趴在窗边数星星i 2024-10-27 06:56:29

putImageData() 不会执行您最初期望的操作:
http://dropshado.ws/post/1244700472/putimagedata-is- a-complete-jerk

putImageData() 直接覆盖画布的像素。因此,如果您在同一画布上绘制其他内容,它不会“覆盖”它,而是会用该区域的像素替换该区域中画布的像素。

我遇到了这个确切的问题并终于找到了原因。

至于解决方案,我还没有尝试过,但看起来很有希望:
为什么 putImageData 这么慢?

[编辑]:< /strong> 我测试了这个方法,它对我来说效果很好,我的数据现在正确显示透明度。

putImageData() does not do what you might first expect:
http://dropshado.ws/post/1244700472/putimagedata-is-a-complete-jerk

putImageData() direct overrides the pixels of the canvas. So if you draw over something else on the same canvas it will not draw "over" it, it will instead replace the pixels of the canvas in the area with it's pixels.

I ran into this exact issue and finally found out why.

As for a solution, I haven't tried this yet but it seems promising:
Why is putImageData so slow?

[EDIT]: I tested this method and it works fine for me, my data is now displaying transparency correctly.

乖乖 2024-10-27 06:56:29

创建后画布是黑色的。首先使其透明:

context.fillStyle = 'rgba(0,0,0,0)';
context.fillRect(0, 0, width, height);

The canvas is black after being created. Make it transparent first with:

context.fillStyle = 'rgba(0,0,0,0)';
context.fillRect(0, 0, width, height);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文