new TouchBar(options)
实验功能
用途:使用指定项目创建新的触摸条,使用 BrowserWindow.setTouchBar
将 TouchBar
加到窗口中
const {app, BrowserWindow, TouchBar} = require('electron')
const {TouchBarLabel, TouchBarButton, TouchBarSpacer} = TouchBar
let spinning = false
//卷轴标签
const reel1 = new TouchBarLabel()
const reel2 = new TouchBarLabel()
const reel3 = new TouchBarLabel()
//旋转结果标签
const result = new TouchBarLabel()
//旋转按钮
const spin = new TouchBarButton({
label: '🎰 Spin',
backgroundColor: '#7851A9',
click: () => {
//忽略已经旋转的点击
if (spinning) {
return
}
spinning = true
result.label = ''
let timeout = 10
const spinLength = 4 * 1000 // 4 seconds
const startTime = Date.now()
const spinReels = () => {
updateReels()
if ((Date.now() - startTime) >= spinLength) {
finishSpin()
} else {
//每次旋转减慢一点
timeout *= 1.1
setTimeout(spinReels, timeout)
}
}
spinReels()
}
})
const getRandomValue = () => {
const values = ['🍒', '💎', '7️⃣', '🍊', '🔔', '⭐', '🍇', '🍀']
return values[Math.floor(Math.random() * values.length)]
}
const updateReels = () => {
reel1.label = getRandomValue()
reel2.label = getRandomValue()
reel3.label = getRandomValue()
}
const finishSpin = () => {
const uniqueValues = new Set([reel1.label, reel2.label, reel3.label]).size
if (uniqueValues === 1) {
//3个相同值
result.label = '💰 Jackpot!'
result.textColor = '#FDFF00'
} else if (uniqueValues === 2) {
// 2个相同值
result.label = '😍 Winner!'
result.textColor = '#FDFF00'
} else {
//没有相同值
result.label = '🙁 Spin Again'
result.textColor = null
}
spinning = false
}
const touchBar = new TouchBar([
spin,
new TouchBarSpacer({size: 'large'}),
reel1,
new TouchBarSpacer({size: 'small'}),
reel2,
new TouchBarSpacer({size: 'small'}),
reel3,
new TouchBarSpacer({size: 'large'}),
result
])
let window
app.once('ready', () => {
window = new BrowserWindow({
frame: false,
titleBarStyle: 'hidden-inset',
width: 200,
height: 200,
backgroundColor: '#000'
})
window.loadURL('about:blank')
window.setTouchBar(touchBar)
})
这样,您就能看到一个新窗口,而触摸条中也将运行相应程序.