我能想到的最简单的方法是使用 Surface 的 setProperties 方法更新 backgroundColor。
在 Surface 的渲染方法中执行此操作,该方法在每个渲染滴答时调用。请记住返回渲染规范(规范 ID)。
不要使用字符串或十六进制值来表示颜色,而是使用接受数字值的 rgb() 或 rgba()。数值是使用 get 方法从 Transitionable 对象中获取的。
在“click”事件处理程序中使用 Transitionable 的 set 方法切换数值。
请记住在设置可转换值(持续时间和缓动曲线)时传递补间选项以获得平滑的动画效果。
这是代码:
var bgColorRed = new Transitionable(0);
var bgColorGreen = new Transitionable(255);
var bgColorBlue = new Transitionable(0);
var colorTweenTime = 500;
var clicked = false;
var square = new Surface({
size: [200, 200],
content: 'Hello.',
properties: {
lineHeight: '200px',
textAlign: 'center'
}
});
square.render = function() {
var red = Math.ceil(bgColorRed.get()),
green = Math.ceil(bgColorGreen.get()),
blue = Math.ceil(bgColorBlue.get());
this.setProperties({
backgroundColor: 'rgb(' + red + ', ' + green + ', ' + blue + ')'
});
return this.id;
};
square.on('click', function() {
if (clicked) {
bgColorRed.set(0, { duration: colorTweenTime, curve: 'easeIn' });
bgColorGreen.set(255, { duration: colorTweenTime, curve: 'easeIn' });
} else {
bgColorRed.set(255, { duration: colorTweenTime, curve: 'easeIn' });
bgColorGreen.set(0, { duration: colorTweenTime, curve: 'easeIn' });
}
clicked = !clicked;
});
jsFiddle 在这里可用:http: //jsfiddle.net/mcr85/6fx9jo9e/