简体   繁体   中英

HTML5 Canvas ImageData incorrect rgb values

I'm working on a paint bucket tool for a drawing application.

I'm using context.getImageData to find out the color values for all the pixels in the canvas.

However, it seems that by default all the rgba values are 0, even though the canvas is white by default. Now my paint bucket tool doesn't work on shapes outlined with black because black has the rgb 0,0,0 and the default canvas image data does as well, even though the canvas is white.

So my question is whether or not I can change the default image data so that it is reflective of the canvas' actual default color (white, or, 255,255,255 ), or how to quickly clear the canvas to that color. A solution I see being possible but incredibly inefficient is, when clearing the canvas, to set every single pixel's values to 255. This causes a couple seconds of lag when performed, though, because of the size of the canvas.

Are there any other alternatives that I am overlooking? Thanks.

An empty canvas is initialized to rgba(0,0,0,0) (ie transparent)

If you want everything to be initialized to white, run something like this.

ctx.fillStyle = '#FFFFFF'; // or 'rgba(255,255,255,1)'
ctx.fillRect(0,0,canvas.width, canvas.height);

For reference in the spec it says:

When the canvas is initialized, its bitmap must be cleared to transparent black.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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