跪拜 Guibai
← Back to the summary

One Vue 3 Component Handles Solid Colors, Gradients, and Canvas Eyedropper Picking

cover.png

Let me start with a real scenario.

The product manager points at the design mockup and says, "Add a color setting here. It needs to pick solid colors, adjust gradients, and also be able to directly pick a color from the canvas."

You open the project and see:

So you end up with three libraries, two sets of state, and a pile of edge-case bugs. A week is gone.

I decided to extract the color-picking capability I had repeatedly refined while working on visualization projects and make it into a standalone Vue 3 component library. It's now open source, MIT licensed, and ready to use out of the box.

Below I'll explain with images what it can do, how to integrate it, and what pitfalls to watch out for.


1. What problems does it actually solve?

The library exposes three components:

Component Purpose
ColorPicker Palette: solid / linear gradient, recently used, eyedropper entry point
EyeDropper Canvas color pick: screenshot + magnifier, click anywhere to sample
SliderColorSetting Gradient color-stop bar, supports add/delete stops, drag, angle rotation, color order flip

Plus a set of utility functions and composables: color parsing/conversion, gradient parsing, recently used colors, and picker sessions.

Here's an overall demo:

demo-overview.png

Compared with common solutions out there, it has several practical strengths:

  1. Solid and gradient are in the same panel — no need to pull in another library for gradients;
  2. Built-in canvas eyedropper — doesn't rely on the browser's native EyeDropper API; it uses screenshot sampling, so you don't have to wait for a specific rendering engine to support it;
  3. No binding to Pinia, JWT, or your store — getUserId is passed in by the host;
  4. SSR renderable — no crash on the server from directly touching window;
  5. Themeable styles — 5 CSS variables cover the theme.

2. Integrate it in 30 seconds

Install:

pnpm add @you-want/color-picker-lib vue element-plus

Peer dependencies are just two: vue ^3.5.0 and element-plus >=2.6.0.

Register Element Plus in your entry file, and explicitly import the library's styles:

import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import '@you-want/color-picker-lib/dist/assets/index.css'
import App from './App.vue'

createApp(App).use(ElementPlus).mount('#app')

This is a common pitfall: importing only the component JS won't load the palette layout styles, and the panel will show up as a bunch of bare elements.

Minimal usage is just this:

<script setup lang="ts">
import { ref } from 'vue'
import { ColorPicker } from '@you-want/color-picker-lib'

const color = ref('#316BFF')
</script>

<template>
  <ColorPicker id="theme-color" v-model="color" />
</template>

Note that id is required and must remain stable and unique within the component's lifecycle. It's used for multi-instance mutual exclusion — only one palette can be open at a time on the same page, to avoid two floating layers stacking on top of each other.


3. Solid-color panel: more than a native color picker

Default expanded view:

palette-solid.png

Looks like SketchPicker? Underneath it does use vue-color's SketchPicker, but it adds a layer of things you actually need in real business scenarios:

What's not supported is stated up front: var(), calc(), pixel color stops, radial gradients, and other CSS Color 4 color spaces. Those need to be converted to standard values by the host before being passed in.


4. Linear gradient: multiple stops + angle + flip

Switch to "Linear Gradient" and the panel gains a color-stop editing area:

palette-gradient.png

What you can do:

Corresponding code:

<script setup lang="ts">
import { ref } from 'vue'
import { ColorPicker, type ColorStop } from '@you-want/color-picker-lib'

const source = ref('linear-gradient(90deg, #ff0000 0%, #00ff00 35%, #0000ff 100%)')
const opacity = ref(100)
const stops = ref<ColorStop[]>([])
</script>

<template>
  <ColorPicker
    id="border-color"
    v-model="source"
    v-model:fill-opacity="opacity"
    :slider-buttons="stops"
    @change-color-set="stops = $event"
  />
</template>

v-model gives you a standard CSS string, which you can pass directly to background, borders, Canvas, or Konva.

There's a design trade-off worth mentioning: the color-stop collection is always written back to the host as a new array. Many canvas libraries (like Konva) rely on array reference changes to trigger redraws. If you do an in-place push/splice and pass back the same array, the canvas won't react. I've stepped on this landmine, so the library internally always uses a new reference.


5. Canvas eyedropper: screenshot + magnifier, point and pick

This is the biggest difference between this library and a typical color picker.

Click the eyedropper button in the panel, the whole canvas area enters pick mode, and a 200×200 magnifier appears next to the mouse:

eyedropper.png

Implementation doesn't call the browser's EyeDropper API. Instead it uses snapdom to screenshot the target area, then samples from a Canvas using screen coordinates. Advantages:

Host-side integration has four steps, and the code is short:

<script setup lang="ts">
import { ref } from 'vue'
import { ColorPicker, EyeDropper, useColorPickerSession } from '@you-want/color-picker-lib'

const color = ref('#316BFF')
const canvasEl = ref<HTMLElement | null>(null)
const pickerRef = ref<InstanceType<typeof ColorPicker> | null>(null)

// Pick session: pick-request → mount EyeDropper → confirm writes back
const session = useColorPickerSession()

function onPickRequest(req: { pickerId: string; color: string }) {
  session.onPickRequest(req)
}

function onPickConfirm(hex: string) {
  const pickerId = session.onPickConfirm(hex)
  if (pickerId) {
    pickerRef.value?.applyPickedColor(hex)
  }
}
</script>

<template>
  <div ref="canvasEl">
    <!-- Your canvas, chart, design mockup, whatever DOM -->
  </div>

  <ColorPicker
    id="picker-1"
    ref="pickerRef"
    v-model="color"
    @pick-request="onPickRequest"
  />

  <!-- Mount the picker overlay only when pending is not empty -->
  <EyeDropper
    v-if="session.pending.value"
    :target="canvasEl!"
    @confirm="onPickConfirm"
    @close="session.onPickClose"
  />
</template>

After confirming, the picked color is written back to the currently active color stop. Look at the image below: the first gradient stop was picked as the canvas background #0B1020, and the rectangle border changed too:

picked-back.png

During picking, Escape, right-click, the exit button, and clicking outside the canvas are the four ways to cancel. Cancelling doesn't change the color, and you can keep picking next time.

One more detail: the screenshot isn't a one-time snapshot of the target rectangle; every move recalculates coordinates using the latest getBoundingClientRect(). So after canvas panning, scrolling, or container animations, the pick point doesn't drift.


6. The pitfall you can't avoid: overall transparency and "effective color"

A design tool will inevitably have this requirement: the gradient itself has color-stop alpha, and on top of that you need an "overall transparency".

If you simply multiply the two alphas together, the data gets polluted: the user drags overall transparency to 0%, then back to 100%, and the original color-stop alphas are gone.

This library separates the two:

<ColorPicker
  id="border-picker"
  v-model="source"
  v-model:fill-opacity="opacity"
  @effective-change="rendered = $event.color"
/>

There's a hard rule: canvas rendering only consumes effectiveChange.color, don't multiply transparency again yourself. Otherwise you get the classic "transparency squared" effect, and colors fade more and more.

There's also a utility function for a rectangle gradient border:

import { horizontalGradientBorderStyle } from '@you-want/color-picker-lib'
<div :style="horizontalGradientBorderStyle(rendered, 8)">
  Rectangle content
</div>

It spreads the multiple color stops horizontally, top and bottom edges are same-direction and same-size, left and right edges use the endpoint colors, and corners don't stack alpha twice. It's handy for low-code canvases and big-screen borders.


7. Recently used colors: multi-user isolation, no mixing up accounts

History colors are stored in localStorage by default, keyed as recenterlyUseColor:v2, max 15 entries plus the current color gives 16 slots.

Two details:

  1. Not persisted when not logged in. When getUserId() returns an empty string, it's only used in memory, not written to local storage;
  2. Isolated per user. Under the same storageKey, different users each have their own history; user A won't see user B's history.
<ColorPicker
  id="theme-color"
  v-model="color"
  :get-user-id="() => currentUser.id"
  storage-key="my-app:recent-colors"
/>

When login state changes, the library first settles the old user's edits, then closes the panel, cancels any active picking, and refreshes history. A's edits won't get recorded to B's account.

Also, session-commit fires only once per "close panel or unmount, and there were changes in this round". It's suitable for analytics or actually committing to the backend, and it won't spam requests while you drag around the color wheel.


8. A few pitfalls hit during development, and fixed along the way

This section is for readers who like implementation details, and it's also the interesting part of iterating to 0.2.6.

1. Eyedropper cursor and sampling point were 13 pixels off

When swapping to a 14×14 SVG eyedropper cursor, the CSS cursor hotspot was set to 13 1, i.e., the tail of the eyedropper. The user saw the tip at the bottom-left, but the actual sampling point was at the top-right, a full 13px off.

Changing it to 0 14 aligned the tip. This bug can't be caught by scripted synthetic mouse events, because synthetic events don't go through the cursor rendering layer; only a real human moving a mouse would notice.

2. Gradient two-way sync failure

Adding/deleting color stops in the panel wouldn't refresh the anchors on the canvas; dragging stops on the canvas would leave the panel data stale. The root cause was still array references and event bridging. The fix unified everything to "always write back a new array + bridge the events between canvas and panel".

3. Radio buttons "disappear" in dark mode

The palette itself is a light panel, but Element Plus's dark variables turned the text and dots for "Solid / Linear Gradient" light-colored too — white on white, invisible. The fix was to pin this area to a light theme, with the selected state still using the main color.

4. Latest color appeared in two slots

A small bug fixed in 0.2.6: the current color always occupies the first slot, and if history also contains the same color, it would render twice. Now it deduplicates by color semantics — solid compares RGBA, gradient compares direction + stops — and the current color still stays fixed in the first slot.


9. Size, tests, and edge cases, honestly stated

Current 0.2.6 build output:

Artifact Size gzip
JS 71.81 kB 20.92 kB
CSS 12.80 kB 3.62 kB

For a component library with screenshot-based eyedropper, gradient editing, and history, that's relatively restrained. Note this is the library's own output, not including Element Plus.

For testing, the repo currently has 15 test files and 196 automated cases covering color parsing, coordinate mapping, SSR, keyboard interaction, tarball consumption, etc. pnpm verify runs tests, type checking, example build, and real npm package consumption in sequence.

But let me be clear about what's not covered, so you don't hit it:

If you just want a "can pick a color" input, honestly the native control is enough. But if you're building a design tool, low-code platform, big-screen visualization, or chart configuration, this library can save you a lot of repetitive work.


10. Finally

Project links one more time:

MIT license, use it freely. If it helps you write one fewer color picker, a Star is the biggest support. If you run into issues or want new features, file an Issue and I'll try to respond.

Also feel free to comment: how does your project currently handle color pickers?