Real Noob
Real Noob

Reputation: 1591

Unable to update HTML5 canvas pixel color using putImageData in JavaScript

Here is my complete code:

<canvas width="1366" height="768"></canvas>
<script> 
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;

for (var i = 0; i < data.length; i += 4) {
      data[i]     = 0;
      data[i + 1] = 0;
      data[i + 2] = 0;
    }
ctx.putImageData(imageData, 0, 0);
</script>

Even though I have set the value of each individual color channel to 0, the canvas remains white as if nothing changed.

This is the only code on the webpage and there is no error in the developer console.

Upvotes: 1

Views: 356

Answers (1)

Mathyn
Mathyn

Reputation: 2620

As noted in the comments your alpha channel is most likely 0 making the canvas transparent. To fix this try the following in your for loop:

for (var i = 0; i < data.length; i += 4) {
   data[i]     = 0;
   data[i + 1] = 0;
   data[i + 2] = 0;
   data[i + 3] = 255;
}

Upvotes: 2

Related Questions