Search code examples
htmljquerycropsprite-sheet

How to Crop a Frame With Jquery no Canvas


I need to make a knight for chess(a new project I'm working on). I have a sprite sheet of all the pieces, but I am stuggling to use just one. I need a single piece in a 130px by 130px square. I chose a knight because why not(doesnt have to be in examples). This is the sprite sheet I'm using. I tried a jQuery script appending a new image, then I tried to resize and stuff, no luck. Then I made a <div> and resized that, but I cannot make the background image the chess sprite with jQuery. That code is:

$('.pieces > .white').append('<div class="white wKnight wK' + wK + '" style="width: 130px; height: 130px"></div>');
$('.wK' + wK).css('background-image', ChessSprites.png)

Html:

<div class="pieces">
  <div class="white"></div>
  <div class="black"></div>
</div>

wK stands for whiteKnight and it starts at one and counts up for each knight made, so each is callable individually. I am aware there are probably better ways than that, but I am still learning, and that is what I understand. I do not want to use canvas, as that will be very excessive and difficult imo.


Solution

  • To set the background of an element to a arbitrary piece of an image you can use the background-position css style.

    $('.pieces > .white').append('<div class="white wKnight wK" style="width: 130px; height: 130px"></div>');
    $('.wK').css({'background-image': 'url(https://i.sstatic.net/2OXx4.png)', 'background-position': '390px 0px'});
    $('.pieces > .black').append('<div class="black bKnight bK" style="width: 130px; height: 130px"></div>');
    $('.bK').css({'background-image': 'url(https://i.sstatic.net/2OXx4.png)', 'background-position': '390px 130px'})
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="pieces">
      <div class="white"></div>
      <div class="black"></div>
    </div>