Home > Net >  How to extract sprites from a spritesheet with pure javascript
How to extract sprites from a spritesheet with pure javascript

Time:10-16

So I have this spritesheet with all of the different tiles from legends of zelda is there a way in which I could get enter in a function like getTile(2,1) and it would return the base64 encoding for the knight?
spritesheet

So far I have tried this

function getTiles() {
  var sprites = new Image();
  sprites.src = 'https://cdn.glitch.me/b3505ee1-a321-48ea-baf5-d84841324af1/d3b13ce6-f5ed-4122-9bd9-37f74d13d470.image.png?v=1634242985542';

  allOverworldTiles = []

  var i = 0;
  for (var top = 0; top < 8 * 17; top  = 17) {
    for (var left = 0; left < 20 * 17; left  = 17) {
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      canvas.width = 16;
      canvas.height = 16;
      ctx.drawImage(sprites, left   1, top   1, 16, 16, 0, 0, 16, 16)
    }
  }
  var dataURL = canvas.toDataURL("image/png");
  var newTab = window.open('about:blank', 'image from canvas');
  newTab.document.write("<img src='"   dataURL   "' alt='from canvas'/>");
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I would prefer if the answer was in vanilla javascript

CodePudding user response:

Some issues on your code...

  • you need an onl oad event to make sure the image has loaded before you can do anything
  • you need sprites.crossOrigin="anonymous" or you will get a Tainted canvas error
  • your logic was not clear, you had a double loop but only one toDataURL outside the loop

Here is a working prototype

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = canvas.height = 16;

var sprites = new Image();
sprites.crossOrigin="anonymous"
sprites.src = 'https://cdn.glitch.me/b3505ee1-a321-48ea-baf5-d84841324af1/d3b13ce6-f5ed-4122-9bd9-37f74d13d470.image.png?v=1634242985542';
sprites.onload = getTiles

function getTile(x, y) {
  ctx.drawImage(sprites, x * 17   1, y * 17   1, 16, 16, 0, 0, 16, 16)
  return canvas.toDataURL("image/png");
}

function getTiles() {
  var knight1 = getTile(2, 1)
  document.write("<img src='"   knight1   "'/>");
  
  var knight2 = getTile(8, 1)
  document.write("<img src='"   knight2   "'/>");
  
  var knight3 = getTile(14, 1)
  document.write("<img src='"   knight3   "'/>");
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related