类:TouchBar触摸条

为本机macOS应用程序创建TouchBar布局

进程: 主进程

new TouchBar(options) 实验功能

用途:使用指定项目创建新的触摸条,使用 BrowserWindow.setTouchBarTouchBar加到窗口中

提醒: 如果您没有自带触控板的MacBook的话,可以使用这个触控板模拟器.

注意: TouchBar API 目前是实验功能,未来可能删除.

下面是个用在摇一摇或老虎机,贩卖机上的简单的带有按钮的触摸条例子:

  1. const {app, BrowserWindow, TouchBar} = require('electron')
  2. const {TouchBarLabel, TouchBarButton, TouchBarSpacer} = TouchBar
  3. let spinning = false
  4. //卷轴标签
  5. const reel1 = new TouchBarLabel()
  6. const reel2 = new TouchBarLabel()
  7. const reel3 = new TouchBarLabel()
  8. //旋转结果标签
  9. const result = new TouchBarLabel()
  10. //旋转按钮
  11. const spin = new TouchBarButton({
  12. label: '🎰 Spin',
  13. backgroundColor: '#7851A9',
  14. click: () => {
  15. //忽略已经旋转的点击
  16. if (spinning) {
  17. return
  18. }
  19. spinning = true
  20. result.label = ''
  21. let timeout = 10
  22. const spinLength = 4 * 1000 // 4 seconds
  23. const startTime = Date.now()
  24. const spinReels = () => {
  25. updateReels()
  26. if ((Date.now() - startTime) >= spinLength) {
  27. finishSpin()
  28. } else {
  29. //每次旋转减慢一点
  30. timeout *= 1.1
  31. setTimeout(spinReels, timeout)
  32. }
  33. }
  34. spinReels()
  35. }
  36. })
  37. const getRandomValue = () => {
  38. const values = ['🍒', '💎', '7️⃣', '🍊', '🔔', '⭐', '🍇', '🍀']
  39. return values[Math.floor(Math.random() * values.length)]
  40. }
  41. const updateReels = () => {
  42. reel1.label = getRandomValue()
  43. reel2.label = getRandomValue()
  44. reel3.label = getRandomValue()
  45. }
  46. const finishSpin = () => {
  47. const uniqueValues = new Set([reel1.label, reel2.label, reel3.label]).size
  48. if (uniqueValues === 1) {
  49. //3个相同值
  50. result.label = '💰 Jackpot!'
  51. result.textColor = '#FDFF00'
  52. } else if (uniqueValues === 2) {
  53. // 2个相同值
  54. result.label = '😍 Winner!'
  55. result.textColor = '#FDFF00'
  56. } else {
  57. //没有相同值
  58. result.label = '🙁 Spin Again'
  59. result.textColor = null
  60. }
  61. spinning = false
  62. }
  63. const touchBar = new TouchBar([
  64. spin,
  65. new TouchBarSpacer({size: 'large'}),
  66. reel1,
  67. new TouchBarSpacer({size: 'small'}),
  68. reel2,
  69. new TouchBarSpacer({size: 'small'}),
  70. reel3,
  71. new TouchBarSpacer({size: 'large'}),
  72. result
  73. ])
  74. let window
  75. app.once('ready', () => {
  76. window = new BrowserWindow({
  77. frame: false,
  78. titleBarStyle: 'hidden-inset',
  79. width: 200,
  80. height: 200,
  81. backgroundColor: '#000'
  82. })
  83. window.loadURL('about:blank')
  84. window.setTouchBar(touchBar)
  85. })

上方代码的运行方法

假设已有终端已打开您期望的例子并打算运行上方的例子,那么你需要这么做:

  1. 将上面的内容以 touchbar.js文件保存到计算机中.
  2. 如果没有安装electron的话,则通过npm安装electron 如 npm install electron.
  3. 在Electron中运行: ./node_modules/.bin/electron touchbar.js

这样,您就能看到一个新窗口,而触摸条中也将运行相应程序.