Region-snap: Drag-to-Select Region Screenshots, Now an npm Package for Vue and React
Preface
This time I'm paying off a debt. The previous article 【Vue3 实战】从0到1封装一个“框选截图”组件,顺便聊聊 html2canvas 的那些“坑” promised to package the drag-select screenshot component as an npm package and open-source it. That promise is now fulfilled. I named the plugin Region-snap. It's open-sourced on GitHub and published to npm at the same time. As the title says, it supports Vue and React, and also JavaScript. Go ahead and use it!
Background
Without further ado, let's talk about the background of this plugin. When building document preview, online readers, or admin systems, we might encounter this kind of requirement:
Users select a region of content on the page, turn it into an image, then upload, save, or send it to an OCR interface.
For example: cropping a question from a scanned document, selecting a table from a PDF page, or cropping a section in a document preview for feedback.
The first reaction is usually: draw a selection box, then use html2canvas to capture the image. That should be enough.
But once you actually integrate it into business, problems gradually surface:
- After the container scrolls, can the selection box and the captured content still align?
- After the document is zoomed, how should coordinates be converted?
- If the PDF is already rendered as a canvas, does it need to be re-rendered?
- After the user finishes selecting, can the selection be moved or resized?
- How do you capture documents inside third-party iframes?
region-snap is a region screenshot library built around these needs: drag to select a region on web content, then convert that region into an image.
Take a look at the actual effect:
Full flow: drag to select content → adjust selection size → click button to generate screenshot.
一、从框选到截图,交互是什么样的?
Take an exam paper preview as an example. The user first drags out a rectangular selection on a question.
After the selection is complete, the component shows the selection size, resize handles, and a business-customizable toolbar.
Step 1: Drag to select. The toolbar follows the selection.
If the first selection wasn't complete, you can continue dragging the handles to enlarge or shrink the selection, or directly move the entire selection.
Step 2: Adjust the selection to include the full question.
After confirming the range, click the button in the toolbar to get the image. The demo page displays the result on the right; in business usage, you can upload, download, or submit it to an OCR interface directly.
Step 3: Generate the screenshot. The output corresponds to the left selection, without the selection box or toolbar.
region-snap provides three packages:
| Package name | Purpose |
|---|---|
@region-snap/core |
Framework-agnostic core |
@region-snap/vue |
Vue 3.3+ component |
@region-snap/react |
React 17+ component |
Let's start with Vue integration.
二、在 Vue 中接入区域截图
Install the component:
npm i @region-snap/vue
Wrap the content you want to select in RegionSnap and get the screenshot method via the toolbar slot:
<script setup lang="ts">
import { RegionSnap } from '@region-snap/vue'
async function upload(
getFile: () => Promise<File | null>,
clear: () => void,
) {
try {
const file = await getFile()
if (!file) return
const body = new FormData()
body.append('file', file)
// Replace with your own upload or OCR interface
const response = await fetch('/api/ocr', {
method: 'POST',
body,
})
if (!response.ok) {
throw new Error('上传失败')
}
clear()
} catch (error) {
console.error('截图或上传失败', error)
}
}
</script>
<template>
<RegionSnap
style="height: 600px"
mask
show-size
:capture-options="{
minWidth: 300,
minHeight: 100,
}"
>
<img
src="/paper.png"
alt="待识别文档"
style="display: block; max-width: 100%"
/>
<template #toolbar="{ getFile, clear, capturing }">
<button
:disabled="capturing"
@click="upload(getFile, clear)"
>
识别文字
</button>
<button @click="clear()">取消</button>
</template>
</RegionSnap>
</template>
Here are a few noteworthy points.
mask shows a mask outside the selection, and show-size displays the selection size. Component styles are auto-injected, so no extra CSS import is needed.
getFile() returns a Promise<File | null>. By default, after the selection is complete, the component starts capturing in the background; if the capture hasn't finished when you call it, the promise waits for the result.
The minWidth and minHeight in the example set the minimum size of the output image. When the selection region is smaller than this, the component pads with a centered space, which suits interfaces that require a specific image size.
Padding does not stretch the original image, nor does it add extra image detail.
region-snap handles the selection and image output; OCR recognition is done by your business interface.
三、React 的接入方式也类似
Install:
npm i @region-snap/react
Define the toolbar via renderToolbar:
import { useState } from 'react'
import { RegionSnap } from '@region-snap/react'
export default function CaptureDemo() {
const [preview, setPreview] = useState<string | null>(null)
return (
<>
<RegionSnap
style={{ height: 600 }}
mask
showSize
renderToolbar={({ getImage, clear, capturing }) => (
<>
<button
disabled={capturing}
onClick={async () => {
try {
const image = await getImage()
if (image) setPreview(image)
} catch (error) {
console.error('截图失败', error)
}
}}
>
生成截图
</button>
<button onClick={clear}>取消</button>
</>
)}
>
<img
src="/paper.png"
alt="待截图文档"
style={{ display: 'block', maxWidth: '100%' }}
/>
</RegionSnap>
{preview && <img src={preview} alt="截图预览" />}
</>
)
}
Both the Vue and React versions provide the same three output forms:
| Method | Return type | Common usage |
|---|---|---|
getImage() |
Data URL | Page preview |
getBlob() |
Blob | Upload, further image processing |
getFile() |
File | File upload |
Output supports PNG, JPEG, and WebP.
Toolbar buttons are defined by the business, so you can swap "Generate screenshot" for "Recognize text", "Save attachment", or "Submit feedback" while reusing the same selection interaction.
四、截图背后,其实有三条路径
In region-snap's implementation, a key choice is: depending on the content and scenario, different screenshot approaches are used.
1. Images and canvas: crop directly when conditions are met
If the selection falls entirely within a qualifying image or canvas, the component first tries to crop from the source.
For a PDF preview, for example, the page may already be rendered as a canvas by pdf.js. The selection can be mapped to pixel coordinates inside the canvas, and drawImage() can crop the corresponding part.
This saves a DOM re-render and also exploits the source's original resolution.
For instance, an image with an original width of 2400 pixels shown at 800 CSS pixels on the page. Assuming no other scaling, if the user selects a 200 CSS-pixel-wide part, after cropping at source resolution the output width is about 600 pixels.
Direct cropping requires conditions. Special image fitting modes, occlusion, or cross-origin resources may make this path unusable, in which case it falls back to the renderer.
2. Ordinary DOM: hand over to the renderer
Text, tables, and mixed-layout content are handled by the lazily loaded html2canvas by default, passing the corresponding selection range.
Therefore, region-snap does not need to first generate a full long screenshot and then crop from that result. However, actual time consumption still depends on DOM complexity, resource loading, and renderer implementation.
The exam paper example earlier demonstrates region screenshot of ordinary DOM content.
The renderer can also be replaced. For example, if the page uses a color syntax that the default html2canvas doesn't support, you can use html2canvas-pro:
import html2canvasPro from 'html2canvas-pro'
import { html2canvasRenderer } from '@region-snap/vue'
const captureOptions = {
renderer: html2canvasRenderer(
{ backgroundColor: null },
html2canvasPro,
),
}
You can also implement your own CaptureRenderer. It receives the content element, selection coordinates, and an output scale, and returns a canvas.
This design separates the selection interaction from image generation: the business can reuse the same selection interaction and choose the rendering method based on the page situation.
3. Cross-origin iframe: share the current tab
Third-party document preview is another case.
For example, when a page embeds a cross-origin iframe like Office Online, DOM-based renderers cannot directly read the content inside.
region-snap provides createScreenCapture() for this: it uses the browser's screen-sharing capability to capture the current tab's display, then crops the selection.
import { createScreenCapture } from '@region-snap/vue'
const screen = createScreenCapture()
// Call from a user click event; the browser will request share authorization
await screen.start()
// Pass screen.renderer to captureOptions.renderer
// Stop sharing when done
screen.stop()
This path captures what the user actually sees, so it can handle visible content inside cross-origin iframes.
According to the project's current documentation, this mode targets desktop Chrome / Edge, requires HTTPS or localhost, and needs user authorization for sharing. A single capture can only get the visible portion, and other popups covering the content may also appear in the screenshot.
五、滚动、缩放和触屏,才是交互里的细节
Drawing a rectangle is not hard; keeping it aligned in a real page is.
region-snap's selection uses this data structure:
interface Region {
x: number
y: number
width: number
height: number
}
These values are relative to the top-left corner of the content area, using layout pixels that have not been scaled by CSS transforms.
This means that when the document is zoomed via transform: scale(), the selection data still describes the same layout region; the component handles converting to screen positions.
Vue can manage the selection with v-model:region:
<RegionSnap v-model:region="region">
<!-- 文档内容 -->
</RegionSnap>
React can use region and onRegionChange as a controlled component.
This also lets the business restore or set the selection programmatically.
However, scaling and re-layout are different things. If content width changes cause text to reflow, old coordinates may point to different content. The component clears the selection by default when it detects a content width change.
For scroll containers, dragging to the edge auto-scrolls and continues extending the selection range.
Touch interaction defaults to "long-press then select", so normal swiping can still scroll. For a dedicated screenshot mode, it can be switched to direct drag-to-select.
六、超过一屏的文档,可以滚动拼接
The shared-tab mode can be further used for long screenshot capture.
After selecting, call startScrollCapture(), the user scrolls the document within the selection, and the component stitches by comparing overlapping content between adjacent frames. When finished, call finishScrollCapture() to get the long image.
The toolbar can show current progress:
<template
#toolbar="{
scrollCapture,
startScrollCapture,
finishScrollCapture,
cancelScrollCapture,
}"
>
<template v-if="scrollCapture">
<span>
{{
scrollCapture.lost
? '请往回滚一点,恢复拼接'
: `已拼接 ${scrollCapture.height}px`
}}
</span>
<button @click="finishScrollCapture()">完成</button>
<button @click="cancelScrollCapture()">取消</button>
</template>
<button v-else @click="startScrollCapture()">
滚动截图
</button>
</template>
This capability requires a renderer that supports scroll capture, such as createScreenCapture().renderer.
Since stitching depends on overlapping frames, scrolling too fast, large blank areas, repeated content, and fixed toolbars within the selection can all affect matching. The current long image height limit is 16384 pixels.
It's best to select the main content area and keep a moderate scroll speed.
七、接入前需要了解的边界
When choosing a screenshot method, you can judge by content:
| Content scenario | Preferred approach |
|---|---|
| Single image, PDF canvas | Direct crop from source |
| Text, table, mixed DOM | Default or custom renderer |
| Visible content in cross-origin iframe | Shared tab capture |
| Long image of cross-origin document | Shared tab plus scroll stitching |
For ordinary DOM screenshot, the fidelity depends on the renderer's support. Cross-origin images also need correct CORS configuration; enabling useCORS alone does not replace the resource server's authorization.
Regarding licensing, the project uses a dual AGPL-3.0 and commercial license. Before closed-source integration, please read the license instructions in the repository; commercial licenses can be obtained by contacting the project.
八、让截图成为业务流程的一部分
Region screenshot is often just the entry point of a business flow.
After a user selects a region, they may want to recognize text, upload an attachment, submit feedback, or just save an image.
region-snap consolidates selection, selection adjustment, toolbar positioning, and image output into a single component, leaving the follow-up actions to the business. For scenarios like document preview, image recognition, and content feedback, you can start with a simple toolbar.
Welcome to try it, and please report compatibility issues in specific pages via Issue.
- Online demo: region-snap website
- Source code: Jacky010/region-snap
- npm: @region-snap/core
Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.
Great article, thanks for sharing.
Thanks 🌹