Search code examples
javascriptxmlhttprequestpngarraybuffer

javascript PNG manipulation


I'm making a site to play card games. The images of the cards are downloaded from the server in one big PNG file. On the client side, using javascript, I want to make multiple elements, one for each card.

var cards = new Array(number of cards);
var request = new XMLHttpRequest();
request.responseType    = "arraybuffer";
//alternatively: request.responseType    = "blob";

request.onreadystatechange = function(){
    var arrayBuffer = this.respons;

    //how do I cut up the arrayBuffer such that i can use something like:

    var urlCreator = window.URL || window.webkitURL;
    var imageUrl = urlCreator.createObjectURL( cards[3] );

    var img = document.getElementById("img");
    img.src = imageUrl;

}
request.open("GET","cardsheet.png",true);
request.send();

arrayBuffer.slice(0,cardWidth) does not work because this returns a new in mutable arrayBuffer, and one card would exit out of multiple arrayBuffer.slice(0,cardWidth). The reason I want to do it like this is such that to load all cards only one request to the server is made. If my idea is not done, can you provide me with an alternative?


Solution

  • You can use CSS to simplify this, simply use the background-position style while setting the background image of the element.

    .card {
       width:100px;
       height:175px;
       background-image:url(http://placekitten.com/300/300);
       background-position:100px 100px;
    }
    

    Demo

    .card {
      width:100px;
      height:175px;
      display:inline-block;
      background-image:url(http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg);
    }
    
    .card.card-1 {
      background-position:0px 0;  
    }
    
    .card.card-2 {
      background-position:-100px 0;  
    }
    
    .card.card-3 {
      background-position:-200px 0;  
    }
    <div class="card card-1"></div>
    <div class="card card-2"></div>
    <div class="card card-3"></div>