javascript - 使用此代码,我将如何在 JavaScript 中为精灵设置动画以在屏幕上闪烁 2 种不同颜色?或者更确切地说,我将如何解决它?
问题描述
我一直在尝试从精灵表中为标题屏幕设置动画。我已经加载了精灵表,但我似乎无法弄清楚为什么动画没有发生。我有一个不需要参数即可运行的更新函数:
function update(){
menu.update
}
let frames = 0
我的代码开头也有。我的问题是在绘制动画或其他内容时。它从动画中绘制第 0 帧,但不绘制第 1 帧。我曾尝试将动画师放在“if”语句下,但经过几次尝试后,我无法让它停止询问参数和/或表达式。(我尝试了一些箭头函数,但我不习惯使用它们,所以我不知道我所做的是对还是错。)
const menu = {
animation : [
{sX: 27, sY: 295},
{sX: 27, sY: 399},
],
x : cvs.width/2 - 118/2,
y : 100,
w : 118,
h : 84,
frame : 0,
// Animator
update : function(){
// Incrementation % incrementation period (speed)
this.frame += frames%5 == 0 ? 1 : 0;
// Iteration of animation--draws 0 then 1 then 0....
this.frame = this.frame%this.animation.lenghth;
},
draw : function(){
let animCounter = this.animation[this.frame];
if(status.current == status.Start){
ctx.drawImage(sprite, animCounter.sX, animCounter.sY, this.w, this.h, this.x, this.y, this.w, this.h);
}
},
}
我很确定问题出在“if”语句中,我可以让它与这个精灵表上的另一个精灵一起工作;它没有“if”语句,但除了源位置等之外的所有其他内容都是相同的。
解决方案
这可能是由于一个简单的错字:
this.frame = this.frame%this.animation.lenghth;
应该读:
this.frame = this.frame%this.animation.length; // removed the "h"
这是一个交替河马的演示:-)
var sprite = document.getElementById('source');
var width = 600,
height = 600,
cvs = document.getElementsByTagName('canvas')[0],
ctx = cvs.getContext('2d');
cvs.width = width;
cvs.height = height;
const menu = {
animation: [{
sX: 27,
sY: 295
},
{
sX: 27,
sY: 399
},
],
x: cvs.width / 2 - 118 / 2,
y: 100,
w: 118,
h: 84,
frame: 0,
frames: 0,
// Animator
update: function() {
// Incrementation % incrementation period (speed)
this.frame += this.frames % 5 == 0 ? 1 : 0;
// Iteration of animation--draws 0 then 1 then 0....
this.frame = this.frame % this.animation.length;
this.draw();
window.setTimeout(function() {
menu.update();
}, 300);
},
draw: function() {
let animCounter = this.animation[this.frame];
//if (status.current == status.Start) {
ctx.drawImage(sprite, animCounter.sX, animCounter.sY);
//}
}
}
menu.update();
<canvas></canvas>
<img id="source"
src="https://mdn.mozillademos.org/files/5397/rhino.jpg"
width="300" height="227" style="display:none;">
推荐阅读
- java - CopyOnWriteList 实现中 removeAll() 的实现问题
- python - 组合 GroupBy 对象(不是输出,而是实际对象)
- c - 我正在尝试将电位器的转换值(张力)实时显示为 4 个 7 段显示器,我该怎么做?
- c# - 如何将 C# 中的 json 字符串反序列化为正确的类型,而无需反序列化两次
- sql - 如何在一个中实现级联删除->许多*从多方面*
- c# - C# 反序列化一个序列化的 JSON 字符串
- haskell - VS Code 未在 Haskell 中显示错误行的标记
- python - 如何让角色在 pygame 中碰到边缘时拖动相机?
- android - Asynctask 内存泄漏警告 Android
- html - 做 HTML 标题 (