简体   繁体   English

HTML5画布图像缓存/ putImageData问题

[英]HTML5 canvas image caching/putImageData questions

I'm using the HTML5 canvas to load a single instance of an image which I then blit multiple times onto a single canvas. 我正在使用HTML5画布加载图像的单个实例,然后我将其多次blit到一个画布上。 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. 我最初的攻击计划是加载图像,将其blit到支持画布,在其上绘制我的修改,然后抓取图像数据并将其缓存以备将来使用。

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. 虽然这有效,但我注意到我的图像(透明的PNG)不能保持透明度。 Instead, when using putImageData to place it onto my front-facing canvas, it is rendered with a black background. 相反,当使用putImageData将其放置在我的前置画布上时,它将以黑色背景呈现。 How do I maintain transparency? 我如何保持透明度?

Any suggestions are welcome! 欢迎任何建议!

putImageData() does not do what you might first expect: http://dropshado.ws/post/1244700472/putimagedata-is-a-complete-jerk putImageData()没有按照你的预期做到: http ://dropshado.ws/post/1244700472/putimagedata-is-a-complete-jerk

putImageData() direct overrides the pixels of the canvas. putImageData()直接覆盖画布的像素。 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? 至于解决方案,我还没有尝试过,但它看起来很有希望: 为什么putImageData这么慢?

[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: 首先使其透明:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM