![](/img/trans.png)
[英]Animating image/3D/sprite with javascript/css3/canvas
[英]Animating sprite frames in canvas
我正在使用canvas元素制作一個小型平台游戲,但我在尋找使用Sprite的最佳方法時遇到了麻煩。
Canvas不支持動畫GIF,所以我不能這樣做,所以我為動畫精靈制作了一個電影膠片,給人以角色正在移動的錯覺。 像這樣: http : //i.imgur.com/wDX5R.png
以下是相關代碼:
function player() {
this.idleSprite = new Image();
this.idleSprite.src = "/game/images/idleSprite.png";
this.idleSprite.frameWidth = 28;
this.idleSprite.frameHeight = 40;
this.idleSprite.frameCount = 12;
this.runningSprite = new Image();
this.runningSprite.src = "/game/images/runningSprite.png";
this.runningSprite.frameWidth = 34;
this.update = function() {
}
var frameCount = 1;
this.draw = function() {
c.drawImage(this.idleSprite, this.idleSprite.frameWidth * frameCount, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, 0, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight);
if(frameCount < this.idleSprite.frameCount - 1) { frameCount++; } else { frameCount = 0; }
}
}
var player = new player();
如您所見,我正在定義空閑子畫面及其幀寬度和幀數。 然后在我的draw方法中,我使用這些屬性來告訴drawImage方法繪制什么幀。 一切正常,但是我對在draw方法之前定義的frameCount
變量不滿意。 看來...駭人又丑陋。 人們會知道有一種方法可以在不跟蹤draw方法外部的框架的情況下達到相同的效果嗎? 甚至可以用更好的替代方法將動畫精靈繪制到畫布上。
謝謝。
您可以根據當前時間的一部分選擇幀,例如
this.draw = function() {
var fc = this.idleSprite.frameCount;
var currentFrame = 0 | (((new Date()).getTime()) * (fc/1000)) % fc;
c.drawImage(this.idleSprite, this.idleSprite.frameWidth * currentFrame, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, 0, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight);
}
這將為您提供一秒的動畫時間(1000是毫秒值)。 根據您的幀頻和動畫,這可能看起來有些生澀,但它並不依賴於持久計數器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.