Web color picker (color straw tool) can suck the color value of every pixel on the web page.

I. Introduction and use

legend

use

import ColorPipette from './color-pipette';
/ / initialization
const pipette = new ColorPipette({
  container: document.body,
  scale: 2.listener: {
    onOk({ color, colors }) => {
      console.log(color, colors); }}});// Start taking color
pipette.start();
Copy the code

Parameters that

Parameter names meaning The default value note
container Want to capture the page DOM element document.body
scale Display pixel ratio 1 The scale for drawing screenshots ranges from 1 to 4. The larger the number, the clearer it is but the slower it is
listener Event listeners onOk: ({color: string; colors: string[][]}) => void
listener.onOk Listen to complete onOk: ({color: string; colors: string[][]}) => void
listener.onChange To monitor changes onChange: ({color: string; colors: string[][]}) => void

Two, implementation method

The realization of color picker is mainly divided into several steps

  1. Webpage screenshot;
  2. Draw a screenshot to canvas, and get the color value of pixel points in the specified area;
  3. Get mouse position, display magnifier and color value;

1. Screenshot of web page

In order to obtain the pixel color of the page, it is necessary to take a screenshot of the whole web page first. For compatibility, we use DOM-to-image to achieve the screenshot function. Source code here: dom-to-image

In the process of use, I found that the DOM-to-image screenshot was very fuzzy, so I copied the source code (only a few hundred lines) and supported setting the resolution.

  • Use the screenshot
import domtoimage from './dom-to-image';

async getPagePng() {
    const base64 = await domtoimage.toPng(this.targetDom, { scale: 2 });
    return base64;
}
Copy the code
  • I’m just going to change the drawing functionscaleThe setting of the
function draw(domNode, options) {
    const { scale = 1 } = options;
    return toSvg(domNode, options)
        .then(util.makeImage)
        .then(util.delay(100))
        .then(function (image) {
            const { canvas, ctx } = newCanvas(domNode, options);
            console.log(canvas, ctx, canvas.width, canvas.height, scale );
            ctx.drawImage(image, 0.0, canvas.width / scale, canvas.height / scale);
            return canvas;
        });

    function newCanvas(domNode, options) {
        const canvas = document.createElement('canvas');
        const { scale = 1 } = options;
        canvas.width = (options.width || util.width(domNode)) * scale;
        canvas.height = (options.height || util.height(domNode)) * scale;
        const ctx = canvas.getContext('2d');
        ctx.scale(scale, scale);
        if (options.bgcolor) {
            ctx.fillStyle = options.bgcolor;
            ctx.fillRect(0.0, canvas.width, canvas.height);
        }

        return{ canvas, ctx }; }}Copy the code
  • dom-to-image.jsThe complete code is as follows:

dom-to-image.js

2. Draw & get pixel color

  • Take a screenshot of Base64 and draw it to canvas
/** * Load base64 image *@param base64
 * @returns* /
export const loadImage = (base64: string) = > {
  return new Promise((resolve) = > {
    const img = new Image();
    img.src = base64;
    img.onload = () = > resolve(img);
    img.onerror = () = > resolve(null);
  });
};


/** * Draw the DOM node to canvas */
async drawCanvas() {
  const base64 = await domtoimage.toPng(this.container, { scale: this.scale }).catch(() = > ' ');
  if(! base64) {return;
  }
  const img = await loadImage(base64);
  if(! img) {return;
  }
  this.ctx.drawImage(img, 0.0.this.rect.width, this.rect.height);
}

Copy the code
  • Gets the color value of a point on the canvas

/** * the rbGA object is converted to a hexadecimal color string *@param rgba
 * @returns* /
export const rbgaObjToHex = (rgba: IRgba) = > {
  let { r, g, b } = rgba;
  const { a } = rgba;
  r = Math.floor(r * a);
  g = Math.floor(g * a);
  b = Math.floor(b * a);
  return ` #${hex(r)}${hex(g)}${hex(b)}`;
};

/** * Gets the color of the mouse pointer */
getPointColor(x: number, y: number) {
  const { scale } = this;
  const { data } = this.ctx.getImageData(x * scale, y * scale, 1.1);
  const r = data[0];
  const g = data[1];
  const b = data[2];
  const a = data[3] / 255;
  const rgba = { r, g, b, a };
  return rbgaObjToHex(rgba);
}
Copy the code
  • Gets the color value of a rectangular region on the canvas
/** * gets the data output by canvas into a two-digit array *@param data
 * @param rect
 * @param scale
 * @returns* /
 const getImageColor = (data: any[], rect: IRect, scale: number = 1) = > {
  const colors: any[] [] = [];const { width, height } = rect;
  for (let row = 0; row < height; row += 1) {
    if(! colors[row]) { colors[row] = []; }const startIndex = row * width * 4 * scale * scale;
    for (let column = 0; column < width; column += 1) {
      const i = startIndex + column * 4 * scale;
      const r = data[i];
      const g = data[i + 1];
      const b = data[i + 2];
      const a = data[i + 3] / 255;
      constcolor = rbgaObjToHex({ r, g, b, a }); colors[row][column] = color; }}return colors;
};

/** * gets a two-digit array of canvas color values *@param ctx
 * @param rect
 * @param scale
 * @returns* /
export const getCanvasRectColor = (ctx: any, rect: IRect, scale: number = 1) = > {
  const { x, y, width, height } = rect;
  const image = ctx.getImageData(x * scale, y * scale, width * scale, height * scale);
  const { data } = image;
  const colors = getImageColor(data, rect, scale);
  return colors;
}
Copy the code

3. Draw the magnifying glass and color values

  • Monitor mouse movement and click events for interactive operation
  • Drawing magnifier
  • Draws the color value and selects the color

/** * Draw the magnifying glass canvas *@param colors
 * @param size
 * @returns* /
 export function drawPipetteCanvas(colors: IColors, size: number) {
  const count = colors.length;
  const diameter = size * count;
  const radius = diameter / 2;
  const { canvas, ctx } = getCanvas({
    width: diameter,
    height: diameter,
    scale: 2.attrs: {
      style: `border-radius: 50%; `,}});if(! ctx) {return;
  }
  // Draw pixels
  colors.forEach((row, i) = > row.forEach((color, j) = > {
    ctx.fillStyle = color;
    ctx.fillRect(j * size, i * size, size, size);
  }));
  // Draw a horizontal line
  for (let i = 0; i < count; i += 1) {
    ctx.beginPath();
    ctx.strokeStyle = '#eee';
    ctx.lineWidth = 0.6;
    ctx.moveTo(0, i * size);
    ctx.lineTo(diameter, i * size);
    ctx.stroke();
  }
  // Draw a vertical line
  for (let j = 0; j < count; j += 1) {
    ctx.beginPath();
    ctx.strokeStyle = '#eee';
    ctx.lineWidth = 0.6;
    ctx.moveTo(j * size, 0);
    ctx.lineTo(j * size, diameter);
    ctx.stroke();
  }
  // Draw a circular border
  ctx.beginPath();
  ctx.strokeStyle = '#ddd';
  ctx.arc(radius, radius, radius, 0.2 * Math.PI);
  ctx.stroke();
  // Draw the center pixel
  ctx.strokeStyle = '# 000';
  ctx.lineWidth = 1;
  ctx.strokeRect(radius - size / 2, radius - size / 2, size, size);
  return canvas;
}


/** * Draw the magnifying glass dom *@param Colors Two-digit array *@param Size Display size of a single pixel *@returns* /
export function drawPipette(colors: IColors, size = 8) {
  const scale = 2;
  const canvasContainer: any = document.createElement('div');
  const canvasContent: any = document.createElement('div');
  const pipetteCanvas: any = drawPipetteCanvas(colors, size);
  canvasContainer.style = `position: relative; `;
  canvasContent.style = `
    position: absolute;
    top: 0;
    left: 0;
    width: ${pipetteCanvas.width / scale}px;
    height: ${pipetteCanvas.height / scale}px;
    border-radius: 50%;
    box-shadow: 0 0 10px 10px rgba(150,150,150,0.2) inset;
  `;
  canvasContainer.appendChild(pipetteCanvas);
  canvasContainer.appendChild(canvasContent);
  return canvasContainer;
}

Copy the code

/** * color block and color value display *@param color
 * @returns* /
export function drawColorBlock(color: string) {
  const colorBlock: any = document.createElement('div');
  colorBlock.style = ` display: flex; align-items: center; Background - color: rgba (0,0,0,0.4); padding: 2px 4px; border-radius: 3px; `;
  colorBlock.innerHTML = `
    <div style="
      width: 20px;
      height: 20px;
      background-color: ${color};
      border-radius: 3px;
      border: 1px solid #eee;
    "></div>
    <div style="
      width: 65px;
      border-radius: 3px;
      color: #fff;
      margin-left: 4px;
    ">${color}</div>
  `;
  return colorBlock;
}

Copy the code

Three, complete source code

The color class

/** ** Date: 2021.10.31 * author: alanyf */
import domtoimage from './dom-to-image.js';
import { drawTooltip, getCanvas, getCanvasRectColor, loadImage, rbgaObjToHex, renderColorInfo } from './helper';
import type { IProps, IRect } from './interface';

export * from './interface';

/** ** ** */
class ColorPipette {
  container: any = {};
  listener: Record<string.(e: any) = > void> = {};
  rect: IRect = { x: 0.y: 0.width: 0.height: 0 };
  canvas: any = {};
  ctx: any;
  scale = 1;
  magnifier: any = null;
  colorContainer: any = null;
  colors: string[] [] = []; tooltipVisible =true;
  useMagnifier = false;
  constructor(props: IProps) {
    try {
      const { container, listener, scale = 1, useMagnifier = false } = props;
      this.container = container || document.body;
      this.listener = listener || {};
      this.rect = this.container.getBoundingClientRect();
      this.scale = scale > 4 ? 4 : scale;
      this.useMagnifier = useMagnifier;
      // Remove the noscript tag, which may cause
      const noscript = document.body.querySelector('noscript'); noscript? .parentNode? .removeChild(noscript);this.initCanvas();
    } catch (err) {
      console.error(err);
      this.destroy(); }}/** * initializes canvas */
  initCanvas() {
    const { rect, scale } = this;
    const { x, y, width, height } = rect;
    const { canvas, ctx } = getCanvas({
      width: rect.width,
      height: rect.height,
      scale,
      attrs: {
        class: 'color-pipette-canvas-container'.style: `
          position: fixed;
          left: ${x}px;
          top: ${y}px;
          z-index: 10000;
          cursor: pointer;
          width: ${width}px;
          height: ${height}px;
        `,}});this.canvas = canvas;
    this.ctx = ctx;
  }
  /** * start */
  async start() {
    try {
      await this.drawCanvas();
      document.body.appendChild(this.canvas);
      const tooltip = drawTooltip('Press Esc to exit');
      document.body.appendChild(tooltip);
      setTimeout(() = >tooltip? .parentNode? .removeChild(tooltip),2000);
      // Add a listener
      this.canvas.addEventListener('mousemove'.this.handleMove);
      this.canvas.addEventListener('mousedown'.this.handleDown);
      document.addEventListener('keydown'.this.handleKeyDown);
    } catch (err) {
      console.error(err);
      this.destroy(); }}/** * end dom destruction, clear event listener */
  destroy() {
    this.canvas.removeEventListener('mousemove'.this.handleMove);
    this.canvas.removeEventListener('mousedown'.this.handleDown);
    document.removeEventListener('keydown'.this.handleKeyDown);
    this.canvas? .parentNode? .removeChild(this.canvas);
    this.colorContainer? .parentNode? .removeChild(this.colorContainer);
  }

  /** * Draw the DOM node to canvas */
  async drawCanvas() {
    const base64 = await domtoimage.toPng(this.container, { scale: this.scale }).catch(() = > ' ');
    if(! base64) {return;
    }
    const img = await loadImage(base64);
    if(! img) {return;
    }
    this.ctx.drawImage(img, 0.0.this.rect.width, this.rect.height);
  }

  /** * handle mouse movement */
  handleMove = (e: any) = > {
    const { color, colors } = this.getPointColors(e);
    const { onChange = () = > ' ' } = this.listener;
    const point = { x: e.pageX + 15.y: e.pageY + 15 };
    const colorContainer = renderColorInfo({
      containerDom: this.colorContainer,
      color,
      colors,
      point,
    });
    if (!this.colorContainer) {
      this.colorContainer = colorContainer;
      document.body.appendChild(colorContainer);
    }
    onChange({ color, colors });
  }

  /** * Handle mouse press */
  handleDown = (e: any) = > {
    const { onOk = () = > ' ' } = this.listener;
    const res = this.getPointColors(e);
    console.log(JSON.stringify(res.colors, null.4));
    onOk(res);
    this.destroy();
  }

  /** * Handle the keyboard by pressing Esc to exit color pickup */
  handleKeyDown = (e: KeyboardEvent) = > {
    if (e.code === 'Escape') {
      this.destroy(); }};/** * Gets the entire column of colors around mouse points */
  getPointColors(e: any) {
    const { ctx, rect, scale } = this;
    let { pageX: x, pageY: y } = e;
    x -= rect.x;
    y -= rect.y;
    const color = this.getPointColor(x, y);
    const size = 19;
    const half = Math.floor(size / 2);
    const info = { x: x - half, y: y - half, width: size, height: size };
    const colors = getCanvasRectColor(ctx, info, scale);
    return { color, colors };
  }

  /** * Gets the color of the mouse pointer */
  getPointColor(x: number, y: number) {
    const { scale } = this;
    const { data } = this.ctx.getImageData(x * scale, y * scale, 1.1);
    const r = data[0];
    const g = data[1];
    const b = data[2];
    const a = data[3] / 255;
    const rgba = { r, g, b, a };
    returnrbgaObjToHex(rgba); }}export default ColorPipette;

Copy the code

Utility methods

import type { IColors, IRect, IRgba } from './interface';

/** * Load base64 image *@param base64
 * @returns* /
export const loadImage = (base64: string) = > {
  return new Promise((resolve) = > {
    const img = new Image();
    img.src = base64;
    img.onload = () = > resolve(img);
    img.onerror = () = > resolve(null);
  });
};

// Convert decimal to hexadecimal
export function hex(n: number){
  return ` 0${n.toString(16)}`.slice(-2);
}

/** * the rbGA object is converted to a hexadecimal color string *@param rgba
 * @returns* /
export const rbgaObjToHex = (rgba: IRgba) = > {
  let { r, g, b } = rgba;
  const { a } = rgba;
  r = Math.floor(r * a);
  g = Math.floor(g * a);
  b = Math.floor(b * a);
  return ` #${hex(r)}${hex(g)}${hex(b)}`;
};

/** * rbGA object converted to RGBA CSS color string *@param rgba
 * @returns* /
export const rbgaObjToRgba = (rgba: IRgba) = > {
  const { r, g, b, a } = rgba;
  return `rgba(${r}.${g}.${b}.${a}) `;
};

/** * Displays color information, including magnifying glass and color value *@param params
 * @returns* /
export const renderColorInfo = (params: any) = > {
  const { containerDom, color, colors, point } = params;
  let container = containerDom;
  const pos = point;
  const n = 7;
  const count = colors[0].length;
  const size = count * (n + 0) + 2;
  if(! container) {const magnifier: any = document.createElement('div');
    container = magnifier;
  }
  if (pos.x + size + 25 > window.innerWidth) {
    pos.x -= size + 25;
  }
  if (pos.y + size + 40 > window.innerHeight) {
    pos.y -= size + 40;
  }
  container.style = `
    position: fixed;
    left: ${pos.x + 5}px;
    top: ${pos.y}px;
    z-index: 10001;
    pointer-events: none;
  `;
  container.innerHTML = ' ';
  const pipette = drawPipette(colors, n);
  const colorBlock = drawColorBlock(color);
  const padding: any = document.createElement('div');
  padding.style = 'height: 3px; ';
  container.appendChild(pipette);
  container.appendChild(padding);
  container.appendChild(colorBlock);
  return container;
}

/** * Draw magnifier *@param Colors Two-digit array *@param Size Display size of a single pixel *@returns* /
export function drawPipette(colors: IColors, size = 8) {
  const scale = 2;
  const canvasContainer: any = document.createElement('div');
  const canvasContent: any = document.createElement('div');
  const pipetteCanvas: any = drawPipetteCanvas(colors, size);
  canvasContainer.style = `position: relative; `;
  canvasContent.style = `
    position: absolute;
    top: 0;
    left: 0;
    width: ${pipetteCanvas.width / scale}px;
    height: ${pipetteCanvas.height / scale}px;
    border-radius: 50%;
    box-shadow: 0 0 10px 10px rgba(150,150,150,0.2) inset;
  `;
  canvasContainer.appendChild(pipetteCanvas);
  canvasContainer.appendChild(canvasContent);
  return canvasContainer;
}

/** * color block and color value display *@param color
 * @returns* /
export function drawColorBlock(color: string) {
  const colorBlock: any = document.createElement('div');
  colorBlock.style = ` display: flex; align-items: center; Background - color: rgba (0,0,0,0.4); padding: 2px 4px; border-radius: 3px; `;
  colorBlock.innerHTML = `
    <div style="
      width: 20px;
      height: 20px;
      background-color: ${color};
      border-radius: 3px;
      border: 1px solid #eee;
    "></div>
    <div style="
      width: 65px;
      border-radius: 3px;
      color: #fff;
      margin-left: 4px;
    ">${color}</div>
  `;
  return colorBlock;
}

/** * Display prompt *@param content
 * @param tooltipVisible
 * @returns* /
export function drawTooltip(content: string, tooltipVisible = true) {
  const tooltip: any = document.createElement('div');
  tooltip.id = 'color-pipette-tooltip-container';
  tooltip.innerHTML = content;
  tooltip.style = `
    position: fixed;
    left: 50%;
    top: 30%;
    z-index: 10002;
    display: ${tooltipVisible ? 'flex' : 'none'}; align-items: center; Background - color: rgba (0,0,0,0.4); padding: 4px 10px; border-radius: 3px; color: #fff; font-size: 20px; pointer-events: none; `;
  return tooltip;
}

/** * Draw the magnifying glass canvas *@param colors
 * @param size
 * @returns* /
 export function drawPipetteCanvas(colors: IColors, size: number) {
  const count = colors.length;
  const diameter = size * count;
  const radius = diameter / 2;
  const { canvas, ctx } = getCanvas({
    width: diameter,
    height: diameter,
    scale: 2.attrs: {
      style: `border-radius: 50%; `,}});if(! ctx) {return;
  }
  // Draw pixels
  colors.forEach((row, i) = > row.forEach((color, j) = > {
    ctx.fillStyle = color;
    ctx.fillRect(j * size, i * size, size, size);
  }));
  // Draw a horizontal line
  for (let i = 0; i < count; i += 1) {
    ctx.beginPath();
    ctx.strokeStyle = '#eee';
    ctx.lineWidth = 0.6;
    ctx.moveTo(0, i * size);
    ctx.lineTo(diameter, i * size);
    ctx.stroke();
  }
  // Draw a vertical line
  for (let j = 0; j < count; j += 1) {
    ctx.beginPath();
    ctx.strokeStyle = '#eee';
    ctx.lineWidth = 0.6;
    ctx.moveTo(j * size, 0);
    ctx.lineTo(j * size, diameter);
    ctx.stroke();
  }
  // Draw a circular border
  ctx.beginPath();
  ctx.strokeStyle = '#ddd';
  ctx.arc(radius, radius, radius, 0.2 * Math.PI);
  ctx.stroke();
  // Draw the center pixel
  ctx.strokeStyle = '# 000';
  ctx.lineWidth = 1;
  ctx.strokeRect(radius - size / 2, radius - size / 2, size, size);
  return canvas;
}

/** * generates canvas *@param param0
 * @returns* /
 export function getCanvas({ width = 0, height = 0, scale = 1, attrs = {} as Record<string.any>}) {
  const canvas: any = document.createElement('canvas');
  Object.keys(attrs).forEach((key) = > {
    const value = attrs[key];
    canvas.setAttribute(key, value);
  });
  canvas.setAttribute('width'.`${width * scale}`);
  canvas.setAttribute('height'.`${height * scale}`);
  canvas.style = `${attrs.style || ' '}; width:${width}px; height:${height}px; `;
  const ctx = canvas.getContext('2d'); ctx? .scale(scale, scale);return { canvas, ctx };
}

/** * gets the data output by canvas into a two-digit array *@param data
 * @param rect
 * @param scale
 * @returns* /
 const getImageColor = (data: any[], rect: IRect, scale: number = 1) = > {
  const colors: any[] [] = [];const { width, height } = rect;
  for (let row = 0; row < height; row += 1) {
    if(! colors[row]) { colors[row] = []; }const startIndex = row * width * 4 * scale * scale;
    for (let column = 0; column < width; column += 1) {
      const i = startIndex + column * 4 * scale;
      const r = data[i];
      const g = data[i + 1];
      const b = data[i + 2];
      const a = data[i + 3] / 255;
      constcolor = rbgaObjToHex({ r, g, b, a }); colors[row][column] = color; }}return colors;
};

/** * gets a two-digit array of canvas color values *@param ctx
 * @param rect
 * @param scale
 * @returns* /
 export const getCanvasRectColor = (ctx: any, rect: IRect, scale: number = 1) = > {
  const { x, y, width, height } = rect;
  // console.log(x, y, width, height);
  const image = ctx.getImageData(x * scale, y * scale, width * scale, height * scale);
  const { data } = image;
  const colors = getImageColor(data, rect, scale);
  return colors;
}

Copy the code

Interface interface


export interface Point {
  x: number;
  y: number;
}

export interface IRect {
  x: number;
  y: number;
  width: number;
  height: number;
}

export type IColors = string[] [].export interface IRgba {
  r: number;
  g: number;
  b: number;
  a: number;
}

export interface IProps {
  container: any; listener? : Record<string.(e: any) = > void>; scale? :number; useMagnifier? :boolean;
}

Copy the code