How to check image data of image in javascript?

840 Views Asked by At

I want to make a minecraft sort of thing in javascript, and I have a textures image already (an image with all of the textures of the block). Is there a way to get the specific pixel data for said image without drawing it on a canvas?

I don't really know how to upload files to stackoverflow, to make the images work, but I have tried anyways. I think I have done it using an image and canvas element, it works about three fourths of the time:

//size of individual textures
var textureWidth = 16;
var textureHeight = 16;
//get the image
var image = document.getElementById("texturesImage");
console.log(image);

//get the image canvas
//or textures canvas or tcanvas
var tcanvas = document.getElementById("textures");
var tctx = tcanvas.getContext("2d");
tcanvas.width = image.naturalWidth;
tcanvas.height = image.naturalHeight;
var imgWidth = image.naturalWidth;
var imgHeight = image.naturalHeight;
console.log(tcanvas.width);
console.log(tcanvas.height);
tctx.drawImage(image, 0, 0);
//accepts a full integer between 0 and 15
function getTextureData(blockID) {
  if (!Number.isInteger(blockID) || blockID < 0 || blockID > 15) {
    console.log(blockID + " is not a valid ID.");
    return (false);
  }
  //get texture x and y
  var tx = blockID % (imgWidth / textureWidth) * textureWidth;
  var ty = Math.floor(blockID / (imgWidth / textureWidth)) * textureHeight;
  //console.log(tx,ty);
  //return image data
  return (tctx.getImageData(tx, ty, textureWidth, textureHeight));
}


console.log(getTextureData(13));
#textures {
  background-color: orange;
}
Hello world

<canvas id="canvas"></canvas>
<canvas id="textures"></canvas>
<image src="/BlockTextures.png" id="texturesImage"></image>

<!--scripts-->
<script src="engine/1setup.js"></script>
<script src="engine/2getTextures.js"></script>
<script src="script.js"></script>

0

There are 0 best solutions below