A lib for text highlighting by using Canvas.

Overview

canvas-highlighter

基于 canvas 实现的文本划词高亮,与文本展示的结构完全解耦,不改变文本内容的 DOM 结构。

Installation

npm install canvas-highlighter

Usage

最简单的实现文本划词直接高亮

import CanvasHighlighter from 'canvas-highlighter'

// container 为页面需要划词高亮区域的 DOM 对象
const container = document.getElementById('container')
const highlighter = new CanvasHighlighter(container)
container.addEventListener('mouseup', () => {
  const range = highlighter.getSelectionRange()
  if (range) highlighter.addRange(range)
})

自定义高亮区域样式

高亮区域采用 konva 库进行渲染,会在划词区域渲染一个 Rect 和底部渲染一个 Line,可通过修改传入 range 对象上的 config 属性进行自定义

const range = highlighter.getSelectionRange()
const { rect, line } = range.config

// 修改矩形填充颜色
rect.fill = 'red'
// 隐藏线段
line.visible = false

highlighter.addRange(range)

监听高亮区域点击

document.addEventListener('click', (event) => {
  // 通过传入点击位置获取 range id
  const id = highlighter.geRangeIdByPointer(event.pageX, event.pageY)
})

更多例子

1. 划词点击高亮

在线演示

源码

2. 实现类似语雀的划词评论功能

在线演示

源码

API

CanvasHighlighter(container [, config])

container

需要划词高亮区域的 DOM 对象,必须在该对象内容渲染完成时再调用 new CanvasHighlighter(container)

config

参数 说明 类型 默认值
position container 要设置的 position 属性 relative / absolute relative
delay container 元素 ResizeObserver 触发函数的防抖 delay number 300
rectFill 矩形默认填充颜色 string rgba(255, 170, 0, 0.2)
lineStroke 线段默认填充颜色 string rgba(255, 170, 0, 1)
strokeWidth 线段默认的宽度 number 2

instance methods

/**
 * 根据 selection 获取 range,未传 selection 则通过 document.getSelection() 获取
 */
getSelectionRange(selection?: Selection | null): IRange | null

/**
 * 根据 selection 获取头尾两个字符的 DOMRect 对象,未传 selection 则通过 document.getSelection() 获取
 */
getSelectionPosition(selection?: Selection | null): { start: DOMRect, end: DOMRect } | null

/**
 * 清空页面所有 range 并渲染传入的 range 列表
 */
renderRanges(ranges: IRange[]): void

/**
 * 添加 range 并渲染
 * @return ture 表示添加成功,false 表示无效 range
 */
addRange(range: IRange): boolean

/**
 * 根据 id 获取 range
 */
getRange(id: string): IRange | null

/**
 * 根据 id 删除 range
 * @return ture 表示删除成功,false 表示未找到
 */
deleteRange(id: string): boolean

/**
 * 重新渲染已存在 range(根据 id 判断)
 */
updateRange(range: IRange): void

/**
 * 获取当前所有 range 的列表
 */
getAllRange(): IRange[]

/**
 * 清除所有 range
 */
clear(): void

/**
 * 根据页面坐标点判断处于哪个 range 范围内,返回该 id
 */
geRangeIdByPointer(x: number, y:number): string | null

Range

interface IRange {
  // 每个 range 的唯一 id,不能重复
  id: string
  // 划词文本内容
  text: string
  // 开始文本节点
  start: IRangeNode
  // 结束文本节点
  end: IRangeNode
  // 高亮区域的渲染配置项,使用 konva 库进行渲染,可自定义
  config: IRangeConfig
}

interface IRangeNode {
  // 从 container 找到该节点的路径数组
  path: number[]
  // 划词开始偏移量
  offset: number
  // 在该文本中划词的
  text: string
}

interface IRangeConfig {
  // 矩形配置项
  rect: {
    // 填充颜色
    fill: string
    // 是否显示
    visible: boolean
    // 自定义 konva 配置,参考 https://konvajs.org/api/Konva.Rect.html#Rect__anchor
    konvaConfig?: Konva.RectConfig
  }
  // 线段配置项
  line: {
    // 线段颜色
    stroke: string
    // 线段宽度
    strokeWidth: number
    // 是否显示
    visible: boolean
    // 自定义 konva 配置,参考 https://konvajs.org/api/Konva.Line.html#Line__anchor
    konvaConfig?: Konva.LineConfig
  }
}
You might also like...

A JavaScript lib with more functions for the normal Date class.

A JavaScript lib with more functions for the normal Date class.

Jan 26, 2022

A Javascript lib about complex

RealComplex.js 一个关于复数的Javascript库 A Javascript lib about complex How to use it? 使用教程 导入与实例化 import { Complex } from './Complex.js'; let x = new Comple

Feb 9, 2022

Portfólio de projetos pessoais feito com NextJs e lib de animação Framer Motion

Portfólio de projetos pessoais feito com NextJs e lib de animação Framer Motion

Portfólio - Carlos Amorim Esse portfólio foi criado para mostrar meus projetos e habilidades. 🚀 Projeto criado com as seguintes tecnologias: ✔️ NextJ

May 12, 2022

I'm trying to create simple program for adding the digital signature to a pdf file with self-signed certificate. I use node-signpdf and pdf-lib library.

pdf-digital-signature-with-node-signpdf-ejs I'm trying to create simple program for adding the digital signature to a pdf file with self-signed certif

Dec 25, 2022

Cross-runtime benchmarking lib and cli

Cross-runtime benchmarking lib and cli

mitata cross-runtime benchmarking lib Install bun add mitata npm install mitata Examples import { run, bench, group, baseline } from 'mitata'; // den

Jan 3, 2023

This lib was created with the aim of simplifying the use of serverless Twilio.

Twilio Functions Utils About This lib was created with the aim of simplifying the use of serverless Twilio, reducing the need to apply frequent try-ca

Nov 8, 2022

Twitter Text Libraries. This code is used at Twitter to tokenize and parse text to meet the expectations for what can be used on the platform.

twitter-text This repository is a collection of libraries and conformance tests to standardize parsing of Tweet text. It synchronizes development, tes

Jan 8, 2023

Obsidian plugin: Type text shortcuts that expand into javascript generated text.

Obsidian plugin: Type text shortcuts that expand into javascript generated text.

Obsidian Plugin - Text Expander JS (open beta) This Obsidian plugin allows the user to type text shortcuts that are replaced by (or "expanded into") j

Dec 27, 2022

A lightweight JavaScript library that renders text in a brilliant style by displaying strings of random characters before the actual text.

A lightweight JavaScript library that renders text in a brilliant style by displaying strings of random characters before the actual text.

cryptoWriter.js A lightweight javascript library which creates brilliant text animation by rendering strings of random characters before the actual te

Sep 13, 2022
Owner
null
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Syntax Highlighter supporting multiple languages, themes, fonts, highlighting from a URL, local file or post text.

Crayon Syntax Highlighter Supports multiple languages, themes, fonts, highlighting from a URL, local file or post text. Written in PHP and jQuery. Cra

Aram Kocharyan 1.1k Nov 26, 2022
Translate text in images using Vision API, Translation API and React with Canvas

manga-translator Manga translator app using Vision API, Translation API Rendered using React and canvas Installation Create a Google Cloud project, en

Huy Le 4 Oct 26, 2022
A refined tool for exploring open-source projects on GitHub with a file tree, rich Markdown and image previews, multi-pane multi-tab layouts and first-class support for Ink syntax highlighting.

Ink codebase browser, "Kin" ?? The Ink codebase browser is a tool to explore open-source code on GitHub, especially my side projects written in the In

Linus Lee 20 Oct 30, 2022
Syntax highlighting, like GitHub

Close up of The Starry Night by Vincent van Gogh (1889) with examples of starry-night over it starry-night Syntax highlighting, like what GitHub uses

Titus 585 Dec 21, 2022
Render (GitHub Flavoured with syntax highlighting) Markdown, and generate CSS for each of GitHub’s themes.

render-gfm Render (GitHub Flavoured with syntax highlighting) Markdown, and generate CSS for each of GitHub’s themes. GitHub Repository npm Package Do

Shaun Bharat 12 Oct 10, 2022
A Bower wrapper for @bartaz modification to the jQuery Term Highlighting plugin.

jQuery.Highlight.js Text highlighting plugin for jQuery. Original code and documentation. Install API Examples Attribution Install How to use this plu

Ilya Radchenko 46 Dec 30, 2022
Highlighting the best apps and builders on the Farcaster community.

FarApps Highlighting the best apps and builders on the Farcaster community. Getting Started This project uses Next.js. Install dependencies and run th

null 15 Dec 30, 2022
Obsidian text generator Plugin Text generator using GPT-3 (OpenAI)

is a handy plugin for Obsidian that helps you generate text content using the powerful language model GP

null 356 Dec 29, 2022