Confusion about properly using putImageData()

Viewed 19

I have images that I am unable to display properly on my canvas due to transparency issues, and in my attempt to fix them I have come across a new problem.

When using my code below, my images all display with a black background. I am unsure how to remove them, after spending time researching. Insight would be helpful!

    drawPiece(x, y, space) {
        ctx.fillRect(x, y, this.squareSize, this.squareSize)
        if (space != null) {
            const img = new Image(this.squareSize, this.squareSize)
            img.src = space.image
            img.onload = () => {
                ctx.drawImage(img, x, y, this.squareSize, this.squareSize)

                let imageData = ctx.getImageData(x, y, this.squareSize, this.squareSize)
                let data = imageData.data
    
                for (let i=0; i<data.length; i+=4) {
                    if (data[i+3] < 255) {
                        data[i] = 255 - data[i];
                        data[i+1] = 255 - data[i+1];
                        data[i+2] = 255 - data[i+2];
                        data[i+3] = 255 - data[i+3];
                    }
                }

                ctx.putImageData(imageData, x, y)
            }
        }      
    }
0 Answers
Related