Pick color from Desktop, in Electron.
Note
On Windows & MacOS will use our native color-picker.
On Linux will use SCROT to get screenshot and pick color from it. The idea is directly borrowed from package desktop-screenshot.
Error will be thrown:
- when try to start multiple color-picker.
- on unsupported platform.
📁 example/
Basic implementation of using DOM Button to trigger color picking,
and pass result back through ipc
.
Try example with:
cd example/
npm install
npm run-dev # for debug with electron
# or
npm run-prod # for electron-packager output
For a more detailed explanation of the example setup, check: example/concept.md
First add this package to your project:
npm install electron-color-picker
Sample function saveColorToClipboard()
:
const { clipboard } = require('electron')
const {
getColorHexRGB,
// for more control and customized checks
DARWIN_IS_PLATFORM_PRE_CATALINA, // darwin only, undefined on other platform
darwinGetColorHexRGB, // darwin only, throw error on other platform
darwinGetScreenPermissionGranted, // darwin only, throw error on other platform
darwinRequestScreenPermissionPopup // darwin only, throw error on other platform
} = require('electron-color-picker')
const saveColorToClipboard = async () => {
// color may be '#0099ff' or '' (pick cancelled with ESC)
const color = await getColorHexRGB().catch((error) => {
console.warn('[ERROR] getColor', error)
return ''
})
console.log(`getColor: ${color}`)
color && clipboard.writeText(color)
}
if (process.platform === 'darwin' && !DARWIN_IS_PLATFORM_PRE_CATALINA) {
const darwinScreenPermissionSample = async () => {
const isGranted = await darwinGetScreenPermissionGranted() // initial check
console.log('darwinGetScreenPermissionGranted:', isGranted)
if (!isGranted) { // request user for permission, no result, and will not wait for user click
await darwinRequestScreenPermissionPopup()
console.warn('no permission granted yet, try again')
return ''
}
const color = await darwinGetColorHexRGB().catch((error) => {
console.warn('[ERROR] getColor', error)
return ''
})
console.log(`getColor: ${color}`)
color && clipboard.writeText(color)
}
}
To pull deeper code for specific platform,
consider direct require/import the platform index
file.
Do read the source code and check the functionality though.
const { // code with simple mutex wrapper
getColorHexRGB,
DARWIN_IS_PLATFORM_PRE_CATALINA,
darwinGetColorHexRGB,
darwinGetScreenPermissionGranted,
darwinRequestScreenPermissionPopup
} = require('electron-color-picker')
const { // platform specific function, with less check
runColorPicker,
DARWIN_IS_PLATFORM_PRE_CATALINA,
darwinRunColorPicker,
darwinGetScreenPermissionGranted,
darwinRequestScreenPermissionPopup
} = require('electron-color-picker/library/darwin/index.js')