Search code examples
javascriptuint8arraymatrix-engine

Construct chess board like texture with Uint8Array


Code:

var options = {
    squareShema: [8,8],
    pixels: new Uint8Array(8 * 8 * 4)
  };
  options.pixels.fill(122);
  var I = 0, localCounter = 0;
  // options.pixels.fill(I ,funny, funny+1);
  for (var funny = 0; funny < 8*8*4; funny+=4) {
    if (funny % 8 == 0) {
      localCounter++;
      if (I == 0) {I=255} else {I=0}
    } else {
      if (I == 0) {I=255} else {I=0}
    }
    options.pixels[funny] = I;
    options.pixels[funny + 1] = I;
    options.pixels[funny + 2] = I;
    options.pixels[funny + 3] = 1;
  }
  console.log(options.pixels)

What ever i do i get vertical never chess board style.

Any suggestion ?

enter image description here


Solution

  • You need to switch colors every 32 iterations, otherwise you'll get lines instead of a chessboard pattern.

    const c = document.getElementById('c')
    var ctx = c.getContext('2d')
    var imageData = ctx.createImageData(8, 8)
    
    let I = 0
    
    // options.pixels.fill(I ,funny, funny+1);
    for (var funny = 0; funny < 8 * 8 * 4; funny += 4) {
      if (funny % 32 == 0) {
        // NEW ROW, INVERT COLORS
        if (I == 0) {
          I = 255
        } else {
          I = 0
        }
      }
      if (I == 0) {
        I = 255
      } else {
        I = 0
      }
      imageData.data[funny] = I;
      imageData.data[funny + 1] = I;
      imageData.data[funny + 2] = I;
      imageData.data[funny + 3] = 255;
    }
    
    ctx.putImageData(imageData, 0, 0);
    
    const img = document.getElementById('i');
    img.src = c.toDataURL();
    <canvas id="c" width="8" height="8"></canvas>
    
    
    <br />
    
    
    <img width="64" height="64" id="i" />