問題描述
javascript PNG操作 (javascript PNG manipulation)
我正在製作一個玩紙牌遊戲的網站。卡片的圖像以一個大的 PNG 文件從服務器下載。在客戶端,使用 javascript,我想製作多個元素,每張卡片一個。
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) 不起作用,因為這會在可變 arrayBuffer 中返回一個新元素,以及一個card 將退出多個 arrayBuffer.slice(0,cardWidth)。我想這樣做的原因是為了加載所有卡只向服務器發出一個請求。如果我的想法沒有完成,你能提供一個替代方案嗎?
參考解法
方法 1:
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>
(by GassyGhost、Patrick Evans)