HTML5 canvas 图像缓存/putImageData 问题
我使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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.
创建后画布是黑色的。首先使其透明:
The canvas is black after being created. Make it transparent first with: