作为较大程序的一部分,我需要有一个按钮,该按钮最初在mouse:down事件中变为绿色,然后在一定时间间隔后自动变为绿色。我编写了以下测试代码,以查看是否可以正常工作。参照canvas.on函数,如果注释掉了最后两行(btnBox.set和btnTxt.set),按钮的确会变为红色,但是如果保留这些行,则按钮的颜色不会改变。在这两种情况下,计时器似乎都可以工作,但是如果注释掉了计时器代码,则没有什么区别。我将不胜感激,以帮助它与计时器一起使用。
var canvas = new fabric.Canvas("cnvs");
// button group
var btnBox = new fabric.Rect({
width: 95, height: 50, left: 250, top: 300, fill: '#00ff80', strokeWidth: 1, stroke: 'black', selectable: false, rx: 20, ry: 20
});
btnTxt = new fabric.Text('START', {
fontSize: 15, fontWeight: 'bold', fill: 'black', left: 270, top: 320, textAlign: 'center', selectable: false
});
var btnGrp = new fabric.Group( [btnBox, btnTxt]);
btnGrp.set('selectable', false);
btnGrp.set('name', 'btnGrp');
canvas.add(btnGrp);
// mouse down
canvas.on('mouse:down', function(options) {
btnName = options.target.name;
if (btnName === 'btnGrp'){
btnBox.set('fill', 'red');
btnTxt.set('fill', 'red');
// timer
var time = 0, elapsed = 0.0;
window.setInterval(function() {
time += 100;
elapsed = Math.floor(time/100) / 10;
if(Math.round(elapsed) === elapsed) { elapsed += '.0'; }
console.log('ELAPSED');
}, 10000);
btnBox.set('fill', '#00ff80'); // doesn't work
btnTxt.set('fill', 'black'); // doesn't work
}
});
答案 0 :(得分:0)
使用group.item(index)从组中获取项目,然后将属性设置为该对象。
演示
var canvas = new fabric.Canvas("cnvs");
// button group
var btnBox = new fabric.Rect({
width: 95,
height: 50,
left: 50,
top: 50,
fill: '#00ff80',
strokeWidth: 1,
stroke: 'black',
selectable: false,
rx: 20,
ry: 20,
originX: 'center',
originY: 'center'
});
btnTxt = new fabric.Text('START', {
fontSize: 15,
fontWeight: 'bold',
fill: 'black',
left: 50,
top: 50,
textAlign: 'center',
selectable: false,
originX: 'center',
originY: 'center'
});
var btnGrp = new fabric.Group([btnBox, btnTxt]);
btnGrp.set('selectable', false);
btnGrp.set('name', 'btnGrp');
canvas.add(btnGrp);
// mouse down
canvas.on('mouse:down', function(options) {
btnName = options.target && options.target.name;
if (btnName === 'btnGrp') {
options.target.item(0).set({
'fill': 'red'
}); // doesn't work
options.target.item(1).set({
'stroke': 'white',
'fill': 'white',
});
setTimeout(function() {
options.target.item(0).set({
'fill': '#00ff80'
}); // doesn't work
options.target.item(1).set({
'stroke': 'black',
'fill': 'black',
});
canvas.renderAll()
console.log('elapsed')
}, 2000);
//btnTxt.set('fill', 'black'); // doesn't work
}
});
canvas{
border:2px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.3/fabric.min.js"></script>
<canvas id='cnvs' width=300 height=300></canvas>