我是画布脚本的新手。我试图在画布中构建一些条件,条件将在条件满足后显示文本。这就是我所做的条件。
if( fictionMeter > 26 && fictionMeter < 37 ) {
ctx.fillStyle = "#e86f14";
ctx.font = "25px Bangers";
ctx.fillText(
"Alert Condition 1",
mx + 55,
my - 25
);
ctx.font = "14px Bangers";
ctx.fillText(
"add some extra condition",
mx - 55,
my - 8
);
}
if( fictionMeter > 37 ) {
ctx.fillStyle = "#d5292b";
ctx.font = "25px Bangers";
ctx.fillText(
"DANGER CONDITION ONE",
mx + 45,
my - 25
);
ctx.font = "14px Bangers";
ctx.fillText(
"DANGER extra condition one",
mx - 10,
my - 8
);
}
ctx.restore();
}
我的问题是如何在其上添加闪烁的文本动画?,文本动画将显示一秒钟,然后隐藏,直到其他条件完成。
答案 0 :(得分:1)
使用自己的动画属性跟踪对象的更简单方法是创建表示对象的对象。这样您就可以使用当前时间独立驱动对象。
例如(见评论):
var ctx = c.getContext("2d"), bg = 0, db = 0.01;
// BlinkText objects which will hold appearance and timings
function BlinkText(txt, x, y, interval) {
this.text = txt;
this.x = x;
this.y = y;
this.interval = interval;
this.font = "bold 20px sans-serif";
this.color = "#f00";
this.active = false;
this.time = 0;
this.toggle = true;
}
// If several instances is to be defined, use prototypal approach
BlinkText.prototype = {
start: function(time) {
this.time = time; // store start time to calc. delta
this.active = true; // enable drawing in render()
this.toggle = true; // reset toggle flag so first check is "on"
},
stop: function() {
this.active = false; // disable drawing in render()
},
render: function(ctx) { // render if active
if (this.active) {
if (this.toggle) { // are we on nor off?
ctx.font = this.font;
ctx.fillStyle = this.color;
ctx.fillText(this.text, this.x, this.y); // render text if on
}
// calc time interval and toggle every other time
var time = performance.now();
if (time - this.time >= this.interval) { // passed interval?
this.time = time; // update start time
this.toggle = !this.toggle; // toggle state
}
}
}
};
// create a couple of instances
var txt1 = new BlinkText("Hello there..", 50, 50, 500);
var txt2 = new BlinkText("This is blinking too", 100, 90, 900);
var txt3 = new BlinkText("All independant, but controlable...", 10, 120, 300);
txt2.color = "#00f"; // set some custom properties
txt3.font = "16px sans-serif";
txt3.color = "#090";
(function loop() {
// draw other stuff
ctx.fillStyle = "hsl(0,0%, " + (bg * 40) + "%)";
ctx.fillRect(0, 0, c.width, c.height);
txt1.render(ctx); // call render() regardless of state
txt2.render(ctx);
txt3.render(ctx);
bg += db;
if (bg <0 || bg > 1) db = -db;
requestAnimationFrame(loop)
})();
bstart.onclick = function() {
txt1.start(performance.now()); // init start with current time
txt2.start(performance.now());
txt3.start(performance.now());
};
bstop.onclick = function() {
txt1.stop();
txt2.stop();
txt3.stop();
};
&#13;
<canvas id=c></canvas><br>
<button id=bstart>Start</button> <button id=bstop>Stop</button>
&#13;