[英]KineticJS: How do I get the Width and Height of a Sprite or Image?
我從URL加載了一個精靈,想要得到精靈的寬度和高度,結果原來寬度和高度始終為零。 我創建了以下示例。
如何獲得子畫面的實際寬度和高度?
我使用精靈示例,並在此處創建了jsfiddle: http : //jsfiddle.net/confile/jVG9t/
這是html代碼:
<div id="container"></div>
<div id="buttons">
<input type="button" id="punch" value="Width">
</div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.1.0.min.js"></script>
Image <br>
<div id="mydiv" ></div>
這是JS代碼:
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
var imageObj = new Image();
imageObj.onload = function() {
var blob = new Kinetic.Sprite({
x: 250,
y: 40,
image: imageObj,
animation: 'idle',
animations: {
idle: [
// x, y, width, height (4 frames)
2,2,70,119,
71,2,74,119,
146,2,81,119,
226,2,76,119
],
punch: [
// x, y, width, height (3 frames)
2,138,74,122,
76,138,84,122,
346,138,120,122
]
},
frameRate: 7,
frameIndex: 0
});
// add the shape to the layer
layer.add(blob);
// add the layer to the stage
stage.add(layer);
// start sprite animation
blob.start();
var frameCount = 0;
blob.on('frameIndexChange', function(evt) {
if (blob.animation() === 'punch' && ++frameCount > 3) {
blob.animation('idle');
frameCount = 0;
}
});
document.getElementById('punch').addEventListener('click', function() {
alert("blob.width: "+blob.width());
}, false);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/blob-sprite.png';
您可以通過請求它的.width
和.height
屬性來獲取整個imageObj
的寬度/高度:
var imageObj = new Image();
imageObj.onload = function() {
var width=imageObj.width;
var height=imageObj.height;
}
如果imageObj是一個Spritesheet,則無法以編程方式獲取該Spritesheet上各個Sprite的X,Y,寬度,高度。 Spritesheet的作者通常會為您提供此信息。 您經常可以查看子畫面並查看其布局。
您的KineticJS演示要求編碼人員知道每個Sprite的x,y,width,height在Spritesheet上的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.