javascriptcanvasputimagedataimagedata

Javascript PutImageData doing nothing


I'm using the following code to replace the canvas with a solid color when run. The issue is that while the image is created it is not mapped to the canvas.

function draw() {
  var canvas = document.querySelector('canvas');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    const width = canvas.width;
    const height = canvas.height;
    var img = ctx.createImageData(width,height);
  for (var i = 0; i < img.data.length; i += 4) {
    img[i] = 20;
    img[i+1] = 125;
    img[i+2] = 0;
    img[i+3] = 255;
  }
  
    ctx.putImageData(img, 0, 0);
}}

Solution

  • You forgot to add .data when trying to access and change each index

    function draw() {
      var canvas = document.querySelector('canvas');
      if (canvas.getContext) {
        var ctx = canvas.getContext('2d');
        const width = canvas.width;
        const height = canvas.height;
        var img = ctx.createImageData(width,height);
      for (var i = 0; i < img.data.length; i += 4) {
        img.data[i] = 20;
        img.data[i+1] = 125;
        img.data[i+2] = 0;
        img.data[i+3] = 255;
      }
      
        ctx.putImageData(img, 0, 0);
    }}
    draw();