Home > OS >  Construct chess board like texture with Uint8Array
Construct chess board like texture with Uint8Array

Time:09-11

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

CodePudding user response:

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" />

CodePudding user response:

Thanks @GrafiCode

This also works:

  var I = 0, localCounter = 0;

  for (var funny = 0; funny < 8*8*4; funny =4) {
    localCounter  ;
    if (I == 50) {I=133} else {I=50}
    if (parseInt(localCounter - 1) % 8 == 0) {
       if (I == 50) {I=133} else {I=50}
    }
    options.pixels[funny] = I;
    options.pixels[funny   1] = I;
    options.pixels[funny   2] = I;
    options.pixels[funny   3] = 1;

  }

const c = document.getElementById('c')
var ctx = c.getContext('2d')
var imageData = ctx.createImageData(8, 8)
let I = 0
let counter = 0
// options.pixels.fill(I ,funny, funny 1);
for (var funny = 0; funny < 8 * 8 * 4; funny  = 4) {
  counter  ;
  if ((counter-1) % 8 == 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" />

  • Related