diff --git a/src/main/common/listener.js b/src/main/common/listener.js index c08abce..4b43e5c 100644 --- a/src/main/common/listener.js +++ b/src/main/common/listener.js @@ -3,6 +3,7 @@ import {exec, spawn} from "child_process"; import robot from "robotjs"; import Api from "./api"; import ioHook from 'iohook'; +import {throttle} from './utils'; const browsers = require("../browsers")(); const {picker, separator, superPanel} = browsers; @@ -72,6 +73,20 @@ class Listener { } init(mainWindow) { + this.fn = throttle(({x, y}, picker) => { + const img = robot.screen.capture(parseInt(x) - 5, parseInt(y) - 5, 9, 9); + + const colors = {} + + for(let i = 0; i< 9; i++) { + colors[i] = {}; + for (let j = 0; j < 9; j++) { + colors[i][j] = img.colorAt(j, i); + } + } + picker.getWindow().webContents.send("updatePicker", colors); + }, 100); + this.colorPicker(); this.initPlugin(); this.lockScreen(); @@ -123,27 +138,12 @@ class Listener { this.closePicker(); }); }); - - ioHook.on('mousemove', e => { let x = e.x let y = e.y if (!picker.getWindow()) return; - let color = "#" + robot.getPixelColor(parseInt(x), parseInt(y)); picker.getWindow().setPosition(parseInt(x) + 10, parseInt(y) + 10); - - - const img = robot.screen.capture(parseInt(x) - 5, parseInt(y) - 5, 9, 9); - - const colors = {} - - for(let i = 0; i< 9; i++) { - colors[i] = {}; - for (let j = 0; j < 9; j++) { - colors[i][j] = img.colorAt(j, i); - } - } - picker.getWindow().webContents.send("updatePicker", colors); + this.fn(e, picker); }) ioHook.on('mouseup', e => { diff --git a/src/main/common/utils.js b/src/main/common/utils.js index 0377ddd..6528a41 100644 --- a/src/main/common/utils.js +++ b/src/main/common/utils.js @@ -19,3 +19,37 @@ export function getData(path, defaultValue) { return defaultValue || undefined; } } + +export function throttle (func, wait, options) { + let context, args, result; + let timeout = null; + let previous = 0; + if (!options) options = {}; + let later = function() { + previous = options.leading === false ? 0 : Date.now(); + timeout = null; + result = func.apply(context, args); + if (!timeout) context = args = null; + }; + return function() { + let now = Date.now(); + if (!previous && options.leading === false) previous = now; + // 计算剩余时间 + let remaining = wait - (now - previous); + context = this; + args = arguments; + if (remaining <= 0 || remaining > wait) { + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + previous = now; + result = func.apply(context, args); + if (!timeout) context = args = null; + } else if (!timeout && options.trailing !== false) { + timeout = setTimeout(later, remaining); + } + return result; + }; +} +