### user
You are a code expert. Please use your professional knowledge to generate accurate and professional responses. Be sure to ensure that the generated code is executable for demonstration purposes. Develop code for a screenshot tool that allows users to capture browser areas through simple button triggers, supporting three modes: selected area, current visible window, and entire webpage. Users should be able to perform simple edits on the screenshots (such as adding text, drawing boxes, marking with arrows). Finally, users should be able to save the screenshot as an image format and download it quickly.
### assistant · thinking
The user wants a screenshot tool. I should build a browser-based screenshot tool. Key challenge: capturing browser screen in a web page. Options:
1. `navigator.mediaDevices.getDisplayMedia()` — screen capture API, allows capturing screen/tab/window. Then crop the selected area.
2. `html2canvas` — for DOM-to-canvas rendering, works for "entire webpage" but requires external library.
For a self-contained executable demo without external dependencies (CDN may be blocked), I could use getDisplayMedia + canvas. But "entire webpage" would then be limited to the visible viewport unless we scroll-stitch.
Better approach: combine both:
- Use `getDisplayMedia` to capture the screen once (user grants permission), then:
- Selected area: crop from the captured frame.
- Visible window: full frame.
- Entire webpage: scroll the page and stitch multiple frames (or use html2canvas if available).
Actually, let me write a robust single-file HTML app. Use CDN for html2canvas with fallback. Hmm, but "executable for demonstration" — I should provide code that runs. Let me design carefully.
Plan: Single HTML file, no build step.
Core features:
1. Three capture modes:
- **Area selection**: overlay a translucent full-screen selection layer over the *page* to let the user drag a rectangle; then capture via getDisplayMedia and crop that rect (mapping CSS px → device px).
- **Visible window**: getDisplayMedia single frame.
- **Entire webpage**: scroll-stitch using getDisplayMedia — scroll to top, capture frame, scroll by viewport height, capture, repeat, stitch onto canvas. Handle fixed elements issues (mention limitations). Alternatively use html2canvas if available.
Actually, an alternative simpler and more reliable "entire webpage" method: use `html2canvas` if loaded. But it's often imperfect. Let me implement scroll-stitch with getDisplayMedia since we already have the stream — that captures the actual rendering, which is nice. Need to handle: hide scrollbars? Fixed headers repeat. We can mitigate by hiding fixed/sticky elements during capture (optional toggle).
Hmm, but the demo page itself is the thing being captured. If the page is the tool, scrolling the tool page... That's a bit odd but works — the tool is a page and the user can capture it. Actually a screenshot tool for "browser areas" — the user would run this page and capture other content. To make the demo self-contained, I'll make the tool page itself have content to capture (a demo article area) plus the toolbar. Actually better: make the tool a floating panel over a demo page with sample content, so users can test all three modes on the demo content.
Let me structure:
- A demo page with sample content (cards, text, images via CSS gradients) to capture.
- A floating toolbar (fixed position, top-right) with buttons: 区域截图 / 可视窗口 / 整页截图.
- After capture, open an editor modal with canvas + tools: text, rectangle, arrow, freehand pen, mosaic? Keep it: 文字, 矩形, 箭头, 画笔, 颜色, 线宽, 撤销, 重做, 清空, 下载 PNG/JPEG, 复制到剪贴板.
Implementation details:
**Capture engine**
```js
async function getStream() {
// reuse existing stream if alive
if (stream && stream.getVideoTracks()[0]?.readyState === 'live') return stream;
stream = await navigator.mediaDevices.getDisplayMedia({
video: { displaySurface: 'browser', frameRate: 30 },
audio: false,
preferCurrentTab: true, // Chrome: prefer current tab
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude'
});
return stream;
}
```
Then `grabFrame()`: create a video element, attach stream, wait for loadedmetadata, play, then draw to canvas.
To make frames "fresh", after seeking/playing we should wait for a new frame. Trick: use `video.requestVideoFrameCallback` if available, else wait ~2 frames with rAF. Let's implement:
```js
async function grabFrame(video) {
await new Promise(r => {
if (video.requestVideoFrameCallback) video.requestVideoFrameCallback(() => r());
else requestAnimationFrame(() => requestAnimationFrame(r));
});
const c = document.createElement('canvas');
c.width = video.videoWidth; c.height = video.videoHeight;
c.getContext('2d').drawImage(video, 0, 0);
return c;
}
```
Note: video.videoWidth reflects the captured surface resolution, which may be scaled (e.g., capture at device pixel ratio). We need to map CSS coordinates to capture pixels. The captured surface is the whole tab content area (viewport) at some resolution. Since the video frame includes only the tab's viewport (when capturing the current tab), the mapping is: scaleX = videoWidth / window.innerWidth, scaleY = videoHeight / window.innerHeight. That's an approximation but works well when capturing current tab. If the user picks a different window/screen, mapping is wrong — I should handle it by asking the user to select the current tab. I'll add instructions.
Better: for area selection, I could let the user select the area on the *captured frame* instead of on the page. That's more robust! Approach: capture the visible frame first, show it in an overlay sized to the viewport, and let the user drag a selection rectangle on the frozen image. Then crop. This works regardless of what surface is captured (screen/window/tab), as long as the captured frame is displayed to scale.
Hmm, but then the selection is over the frozen screenshot, which is nice UX (like Windows Snipping Tool). But if the user captured the whole screen, the frozen image is the screen — selecting an area there is fine.
But there's a subtlety: mapping the displayed frozen image coords → source pixels. If I display the frozen image with CSS width = window.innerWidth (or fit), the scale factor = frame.width / displayedWidth. Fine.
I'll do: 区域截图 → capture frame → show full-screen overlay with the frozen frame → user drags rectangle → confirm → crop → editor.
For 可视窗口: capture frame → but should it crop to the browser viewport? If user captured the current tab, the frame IS the viewport. Just use the full frame. Good.
For 整页: scroll-stitch. Steps:
1. Remember scroll position, hide scrollbar?
2. Compute total height = document.documentElement.scrollHeight.
3. Hide fixed/sticky elements (optional, via a class that sets visibility:hidden) — actually better to keep them only in the first frame? Common approach: hide them.
4. For each scroll position from 0 to max, scroll, wait for frame, grab frame, draw at y offset.
5. Restore scroll & elements.
Issue: the capture surface may be the whole screen/monitor, not just the tab. Then stitching is wrong. We need the tab-only capture. Chrome's `preferCurrentTab: true` + `selfBrowserSurface: 'include'` helps. Also we can crop the frame to the tab viewport if we know the tab's position on screen — we don't.
Alternative for full page: use html2canvas. Hmm. Given complexity, maybe I offer both: try html2canvas if available (loaded from CDN), else fall back to scroll-stitch. That's more code. Let me think about what's most valuable.
I think for a demonstration, scroll-stitch with getDisplayMedia is fine, and I'll note the requirement to capture "当前标签页" (current tab). Actually there's an even better approach for full-page: use the **Chrome DevTools Protocol**? Not available in a page.
OK let me go with getDisplayMedia for all three, with scroll-stitch for full page. I'll add clear instructions: 选择"当前标签页"以获得最准确的区域映射。
Actually, let me reconsider: for the full-page stitch, when capturing the current tab, the video frame = viewport. videoHeight/window.innerHeight ratio gives the DPR-ish scale. So drawing each frame at (0, scrollY * scale) works. Good.
Handling `window.scrollTo` smooth behavior: use `window.scrollTo({top: y, behavior: 'instant'})`.
Also need to wait for the scroll to actually render and for the capture to update. Use double rAF + requestVideoFrameCallback + small delay (e.g., 60ms). Add a delay of ~100ms per frame for reliability.
Also `scrollHeight` may be less than viewport → single frame.
Let's also handle: if page has `overflow: hidden` etc. Fine.
**Editor**
Canvas-based editor. State:
- `baseImage` (the cropped screenshot as an ImageBitmap/HTMLImageElement or canvas)
- `annotations` array of objects: {type:'rect'|'arrow'|'pen'|'text', ...}
- Redo/undo via history stack of annotation snapshots (simple: push deep copies).
Rendering: redraw base + all annotations each frame (or draw incrementally for pen for performance — simpler to redraw fully; images could be big, but ok. Actually redrawing a big image every mousemove could be slow. Let's use two canvases: a base canvas with the image, and an overlay canvas for annotations. Overlay redraw is cheap. Undo = clear overlay and redraw all annotations. Good.
Actually simpler: single visible canvas for display = base canvas + overlay canvas stacked absolutely. Export = combine into one canvas.
Editor UI:
- Tool buttons: 选择/移动? no. 矩形, 箭头, 文字, 画笔, 橡皮? Keep: 矩形、箭头、文字、画笔、马赛克(optional). Add 撤销/重做/清空.
- Color palette + line width slider.
- Text: click on canvas → prompt/inline input. Use a simple approach: click → create a floating input positioned at click, type, press Enter/click elsewhere → commit as annotation. Let's implement with a contenteditable/input overlay. Simpler: use `prompt()`. But prompt is ugly and may be blocked. Let's do inline input overlay — moderate complexity but nicer. I'll do inline input.
Hmm, to keep code manageable but complete, let me do the inline input overlay with absolute positioning.
- Arrow drawing: line + arrowhead.
- Rect: stroke rect (or filled?). Stroke with lineWidth.
- Pen: freehand path with quadratic smoothing (just lineTo is fine).
- Save: canvas.toBlob → download link. Formats: PNG / JPEG (quality). Also 复制到剪贴板 via navigator.clipboard.write ClipboardItem.
- Also allow "重新编辑"? Not needed.
Also maybe a "水印"? no.
Let me also add keyboard shortcuts: Ctrl+Z undo, Ctrl+Shift+Z redo, Esc close.
**Area selection overlay**
Full-screen fixed overlay with the frozen screenshot as background image (scaled to viewport), a dark mask with a clear rectangle, and size label. Mouse down/move/up to draw. Enter to confirm, Esc to cancel, double-click? Let's do: on mouseup, if the rect is big enough, show a small toolbar with "确认/取消/重选". Simpler: after drag, show buttons "✓ 确认" and "✕ 取消" near the selection, plus allow re-drag to redo.
Let me implement: overlay with canvas showing the frozen frame at viewport size, mask drawn on top. Drag to select. Then buttons appear. Confirm → crop.
Now, mapping: The frozen frame is displayed as `object-fit: contain`? If I set the image to fill the whole viewport exactly, it distorts if aspect differs. Better: draw the frame into an overlay canvas sized to window.innerWidth x window.innerHeight, stretched. Slight distortion but coordinates map linearly: sourceX = displayX * frame.width / window.innerWidth. Since the frame from the current tab has the same aspect ratio, no distortion. For other surfaces, distortion occurs but mapping still "works" visually.
Hmm, but stretching looks bad if capturing whole screen. Alternative: use object-fit: contain and compute offsets. More code. Let me do "contain" properly — it's not that much:
```
const scale = Math.min(vw / fw, vh / fh);
const dw = fw * scale, dh = fh * scale;
const dx = (vw - dw)/2, dy = (vh - dh)/2;
```
Display the image at dx,dy with dw,dh. Selection coords relative to image → source = (x - dx)/scale.
Yes, let's do that. It's cleaner and handles all surfaces.
**Demo page content**
Add sample content: header, cards with gradients, text paragraphs, a table maybe, so full-page capture has scrollable content. And the toolbar fixed at top-right (excluded from capture? It will appear in captures. For area/visible it's fine—the user can choose. For full page, the toolbar is fixed and would repeat/stick. I'll hide the toolbar during full-page capture (set visibility hidden), since it's our own UI. Also hide the selection overlay obviously.
Actually for full-page stitching, I'll hide elements with `data-capture-ignore` attribute. The toolbar has it.
Let me now write the code.
```html
网页截图工具...
...
...
...
```
Let me write the JS carefully.
```js
/* ============ 基础工具 ============ */
const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
const sleep = ms => new Promise(r => setTimeout(r, ms));
const nextFrame = () => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
```
Capture module:
```js
const Capture = (() => {
let stream = null;
let video = null;
async function ensureStream() {
if (stream && stream.getVideoTracks().some(t => t.readyState === 'live')) return stream;
if (!navigator.mediaDevices?.getDisplayMedia) {
throw new Error('当前浏览器不支持屏幕捕获 API(getDisplayMedia),请使用 Chrome / Edge 最新版。');
}
stream = await navigator.mediaDevices.getDisplayMedia({
video: { frameRate: 30, width: { ideal: 4096 }, height: { ideal: 4096 } },
audio: false,
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
systemAudio: 'exclude'
});
stream.getVideoTracks()[0].addEventListener('ended', () => { stream = null; video = null; });
video = document.createElement('video');
video.muted = true;
video.playsInline = true;
video.srcObject = stream;
await video.play();
await new Promise(res => {
if (video.videoWidth) return res();
video.addEventListener('loadedmetadata', res, { once: true });
});
return stream;
}
...
})();
```
Careful: `video.play()` may need the video to be in DOM in some browsers? Generally, muted + playsInline works without DOM in Chrome. To be safe, append to a hidden container. Let's append with style position fixed, width 1px, opacity 0. Actually `display:none` may prevent frames. Use `position:fixed;left:-9999px;width:2px;height:2px;opacity:0;pointer-events:none`. Hmm, that could still be captured if capturing the screen... it's tiny and off-screen. Fine.
Also note: `video.videoWidth` might be 0 until metadata loads.
grabFrame:
```js
async function grabFrame() {
await ensureStream();
// 等待一帧新数据
await new Promise(res => {
let done = false;
const finish = () => { if (!done) { done = true; res(); } };
if (typeof video.requestVideoFrameCallback === 'function') {
video.requestVideoFrameCallback(() => finish());
setTimeout(finish, 500); // 兜底
} else {
setTimeout(finish, 80);
}
});
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
return canvas;
}
```
Hmm, requestVideoFrameCallback fires on the next new frame, which is good.
Also for stitching we need repeated grabs; requestVideoFrameCallback each time works.
**Full page capture:**
```js
async function captureFullPage(onProgress) {
await ensureStream();
const scaleX = video.videoWidth / window.innerWidth;
const scaleY = video.videoHeight / window.innerHeight;
const scale = Math.min(scaleX, scaleY); // assume uniform
const docEl = document.documentElement;
const totalHeight = Math.max(docEl.scrollHeight, document.body.scrollHeight, window.innerHeight);
const viewportH = window.innerHeight;
const maxScroll = totalHeight - viewportH;
const originalScroll = window.scrollY;
const hidden = hideFixedElements();
const frames = [];
let y = 0;
const step = viewportH; // 每次滚动一屏(可能有重叠,用 step = viewportH - overlap)
...
}
```
Wait: `video.videoHeight / window.innerHeight` — if capturing the current tab, the video frame height corresponds to the tab's viewport height (content area). Yes approximately. But Chrome's tab capture might include the whole browser window? With `preferCurrentTab` + tab capture, it's the tab content area. Good.
But wait — with `getDisplayMedia` from a page, when the user picks "当前标签页", Chrome shows the tab's content. The video dimensions ≈ viewport size * devicePixelRatio (capped). So scale ≈ dpr.
Stitching: for each scroll position y, capture a frame and draw it at (0, y*scale) in the output canvas, with height viewportH*scale. Last frame may exceed — clip.
Number of frames: `Math.ceil(totalHeight / viewportH)`. Positions: 0, vh, 2vh, ... but last position should be maxScroll (to avoid blank). Use `positions = []` loop: for (let pos = 0; pos < totalHeight; pos += viewportH) positions.push(Math.min(pos, maxScroll)). Then dedupe.
Overlap: use exact viewport steps and draw each frame fully at its scroll offset; overlapping regions will be overwritten identically (same content) except fixed elements. Good. But there might be slight rendering differences; acceptable.
Hmm — one issue: when scrolled to bottom, the frame content corresponds to scroll position maxScroll, and we draw it at y = maxScroll*scale. Its bottom = (maxScroll + viewportH)*scale = totalHeight*scale. Correct.
hideFixedElements: find elements with computed position fixed or sticky, set visibility hidden, remember, restore later. But this hides sticky headers that might be part of the content... For full-page it's usually desired. I'll make it optional with a checkbox "整页截图时隐藏固定元素". Default on.
Careful: the toolbar itself is fixed; hiding it is good.
```js
function hideFixedElements() {
const list = [];
$$('body *').forEach(el => {
if (el.hasAttribute('data-capture-ignore')) return; // will handle separately
const pos = getComputedStyle(el).position;
if (pos === 'fixed' || pos === 'sticky') {
list.push([el, el.style.visibility]);
el.style.visibility = 'hidden';
}
});
return () => list.forEach(([el, v]) => el.style.visibility = v);
}
```
That's O(n) over all elements, fine for a demo. But `$$('body *')` on a big page could be many. Acceptable.
Also hide our own UI: `[data-capture-ignore]` elements → set visibility hidden during capture.
Also hide scrollbar? Can't easily. The captured frame includes the scrollbar if the page has one... Actually tab capture doesn't include the browser scrollbar (it's part of the browser chrome, not the page). Hmm, Chrome's page scrollbar IS part of the page rendering for overlay scrollbars. With classic scrollbars, the scrollbar takes space within the viewport, and tab capture includes it? I believe Chrome's tab capture captures the page content including the scrollbar area... Actually no — the scrollbar is rendered by the browser and typically excluded from tab capture. Let's not worry; but to be safe, we could hide the page scrollbar during full-page capture by setting `document.documentElement.style.overflow = 'hidden'`? That would change layout (width shift). Not good. Let's leave it; mention it.
Hmm, actually there's a real risk: if the scrollbar is captured, the right edge shows a scrollbar. Minor. Alternatively set `overflow-y: scroll` with `scrollbar-width: none`? Changes layout. Skip.
**Progress UI**: show a small toast "正在拼接 3/8".
**Now the area selector.**
```js
function selectArea(frameCanvas) {
return new Promise(resolve => {
// build overlay
...
});
}
```
Implementation: create a fixed overlay div (z-index 99999), inside it an `` (dataURL of frame) positioned with contain-fit, plus a canvas for the mask, plus hint text, plus confirm buttons.
Actually simpler: draw the frame into a full-viewport canvas with the contain-fit, then draw the mask on top. Use a single canvas for everything and redraw on mousemove. Frame could be large (e.g., 2560x1440) drawn to a 1920x1080 canvas — fine performance-wise for mousemove? Redrawing a full-screen image each mousemove might be a bit heavy but ok on modern hardware. Alternative: use two layers — an `` (or a canvas with the frame drawn once) as the base, and a transparent canvas on top for the mask. That's better. Let's do that.
Structure:
```html
...
```
Base canvas sized to window.innerWidth x window.innerHeight (CSS px, with DPR scaling for crispness? Let's use DPR for crispness: canvas.width = vw*dpr etc., ctx.scale(dpr,dpr)). Hmm, adds complexity. Let's keep DPR scaling — it's just a couple of lines and makes it look sharp.
Actually let's simplify: base canvas width/height = vw, vh (CSS pixels), CSS size = vw, vh. The image is drawn scaled — slight blur on HiDPI. Acceptable? For a screenshot tool, the preview quality matters a bit but the final crop uses the original frame, so it's fine. I'll add DPR for polish.
Hmm, keep it simple and robust: I'll use DPR.
Let me write:
```js
function openSelector(frameCanvas) {
return new Promise((resolve) => {
const vw = window.innerWidth, vh = window.innerHeight;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const wrap = document.createElement('div');
wrap.className = 'shot-overlay';
wrap.innerHTML = `
拖动鼠标框选区域 · Enter 确认 · Esc 取消
`;
document.body.appendChild(wrap);
...
});
}
```
Compute fit:
```js
const fw = frameCanvas.width, fh = frameCanvas.height;
const scale = Math.min(vw / fw, vh / fh);
const dw = fw * scale, dh = fh * scale;
const dx = (vw - dw) / 2, dy = (vh - dh) / 2;
```
Draw base:
```js
const base = wrap.querySelector('.shot-base');
base.width = vw * dpr; base.height = vh * dpr;
base.style.width = vw + 'px'; base.style.height = vh + 'px';
const bctx = base.getContext('2d');
bctx.setTransform(dpr,0,0,dpr,0,0);
bctx.fillStyle = '#0b0d12'; bctx.fillRect(0,0,vw,vh);
bctx.drawImage(frameCanvas, dx, dy, dw, dh);
```
Mask canvas same size, and draw:
```js
function drawMask(sel) {
mctx.setTransform(dpr,0,0,dpr,0,0);
mctx.clearRect(0,0,vw,vh);
mctx.fillStyle = 'rgba(8,10,16,0.55)';
mctx.fillRect(0,0,vw,vh);
if (sel && sel.w > 0 && sel.h > 0) {
mctx.clearRect(sel.x, sel.y, sel.w, sel.h);
mctx.strokeStyle = '#4c8dff'; mctx.lineWidth = 1.5;
mctx.strokeRect(sel.x+.5, sel.y+.5, sel.w-1, sel.h-1);
// 尺寸标签
...
// 网格线/九宫格? skip
}
}
```
Wait: `clearRect` on the mask canvas removes the dim, revealing the base canvas below. Yes, since mask canvas is transparent above base.
Mouse handling on wrap:
```js
let start = null, sel = null, dragging = false;
wrap.addEventListener('mousedown', e => {
if (e.target.closest('.shot-actions')) return;
dragging = true;
start = { x: e.clientX, y: e.clientY };
sel = { x: start.x, y: start.y, w: 0, h: 0 };
actions.hidden = true;
drawMask(sel);
});
window.addEventListener('mousemove', onMove);
window.addEventListener('mouseup', onUp);
```
Clamp selection to the image area (dx..dx+dw, dy..dy+dh). Yes, clamp.
On mouseup: if w>5 && h>5, show actions with size label; else reset.
Confirm: map to source pixels:
```js
const sx = (sel.x - dx) / scale;
const sy = (sel.y - dy) / scale;
const sw = sel.w / scale;
const sh = sel.h / scale;
```
Then crop from frameCanvas. Round and clamp.
Return cropped canvas.
Cleanup: remove listeners, remove wrap.
**Editor**
Modal with:
- header: title + 撤销/重做/清空 + close
- toolbar row: tools (矩形/箭头/文字/画笔), color swatches, line width,
- canvas stage (scrollable if image big)
- footer: 文件名?, 格式选择 PNG/JPEG, 质量, 下载, 复制
Let's implement the editor as a class-ish module.
```js
const Editor = (() => {
let baseCanvas, stage, viewCanvas, drawCanvas, ctx;
let annotations = [];
let redoStack = [];
let current = null; // in-progress annotation
let tool = 'rect';
let color = '#ff3b30';
let lineWidth = 3;
let scale = 1;
...
})();
```
Two stacked canvases inside a stage div: `view` (base image) and `draw` (annotations). Both with the same pixel size as the image, but CSS size = image size * displayScale (to fit the modal). Use CSS transform? Simpler: set canvas width/height = image size, and CSS width/height = imageSize * displayScale px. Mouse coords → image coords via rect and ratio.
Let me set displayScale so the image fits within the available stage area (max 90vw, 70vh).
```js
const maxW = window.innerWidth * 0.86, maxH = window.innerHeight * 0.66;
const displayScale = Math.min(1, maxW / img.width, maxH / img.height);
```
Then canvas element CSS size = img.width*displayScale.
Mouse handling on the draw canvas:
```js
function toImageCoords(e) {
const r = drawCanvas.getBoundingClientRect();
return { x: (e.clientX - r.left) * (drawCanvas.width / r.width), y: (e.clientY - r.top) * (drawCanvas.height / r.height) };
}
```
Annotation types:
- rect: {type:'rect', x, y, w, h, color, lineWidth}
- arrow: {type:'arrow', x1,y1,x2,y2,color,lineWidth}
- pen: {type:'pen', points: [...], color, lineWidth}
- text: {type:'text', x, y, text, color, fontSize}
Render function:
```js
function renderAnnotations(target = dctx) {
target.clearRect(0,0,drawCanvas.width, drawCanvas.height);
const all = current ? [...annotations, current] : annotations;
all.forEach(a => drawAnnotation(target, a));
}
```
drawAnnotation:
```js
function drawAnnotation(ctx, a) {
ctx.save();
ctx.lineCap = 'round'; ctx.lineJoin = 'round';
ctx.strokeStyle = a.color; ctx.fillStyle = a.color;
ctx.lineWidth = a.lineWidth * (a.scaleFix || 1);
...
}
```
Hmm, line width: annotations are stored in image coordinates, so line width in image px. If the image is large and displayed small, lines look thin. Better to store lineWidth in "display" units and multiply by (imageWidth/displayWidth)? Simpler: define lineWidth relative to image size — use `lineWidth = uiLineWidth * (image.width / 1000)` scaled? Hmm.
Let me just store lineWidth in image pixels directly, where the UI slider value maps to `sliderValue * (imageWidth / displayWidthOfCanvasInCSS)`. Ugh.
Simplest robust approach: store `lineWidth` as a fraction of image width: `lw = uiWidth / displayScale`? Since displayScale = cssWidth/imageWidth, then image px per css px = 1/displayScale. So a 3px-wide line on screen = 3/displayScale image px. That keeps visual consistency. Let's do that: when creating an annotation, `lineWidth = uiLineWidth / displayScale`.
Similarly font size: `fontSize = uiFontSize / displayScale`.
OK.
Arrow drawing:
```js
function drawArrow(ctx, a) {
const {x1,y1,x2,y2,lineWidth} = a;
const headLen = Math.max(lineWidth * 4, 12);
const angle = Math.atan2(y2-y1, x2-x1);
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2 - Math.cos(angle)*headLen*0.5, y2 - Math.sin(angle)*headLen*0.5);
ctx.stroke();
// head
ctx.beginPath();
ctx.moveTo(x2,y2);
ctx.lineTo(x2 - headLen*Math.cos(angle - Math.PI/7), y2 - headLen*Math.sin(angle - Math.PI/7));
ctx.lineTo(x2 - headLen*Math.cos(angle + Math.PI/7), y2 - headLen*Math.sin(angle + Math.PI/7));
ctx.closePath();
ctx.fill();
}
```
Text: draw with font `bold ${fontSize}px sans-serif`. Add a subtle shadow/stroke for legibility? Add background? Let's add a white outline via strokeText with white 3px? Might look odd on light bg. Let's just draw text with a slight shadow.
Text input: when tool==='text' and user clicks, create an `` positioned over the canvas at the click point, styled with the current color and font size. On Enter or blur, commit.
Positioning the input: use the stage container with position relative, and place the input at `left: (x*displayScale)px; top: (y*displayScale)px`. Wait — x is in image coords, so CSS offset = x * displayScale. Yes.
The input's font-size in CSS = uiFontSize px (matching visual). Good.
Then commit: annotation {type:'text', x, y: y + fontSize (baseline), text, color, fontSize: uiFontSize/displayScale}.
Hmm, for text I need to store both the image-space font size. `fontSize = uiFontSize / displayScale`.
Undo/redo: snapshot approach.
```js
function pushHistory() { redoStack = []; }
function undo() { const a = annotations.pop(); if (a) redoStack.push(a); render(); }
function redo() { const a = redoStack.pop(); if (a) annotations.push(a); render(); }
```
Simple.
Export:
```js
function exportCanvas(type = 'image/png', quality = 0.92) {
const out = document.createElement('canvas');
out.width = baseCanvas.width; out.height = baseCanvas.height;
const octx = out.getContext('2d');
if (type === 'image/jpeg') { octx.fillStyle = '#fff'; octx.fillRect(0,0,out.width,out.height); }
octx.drawImage(baseCanvas, 0, 0);
// 重新在导出上下文里绘制标注(矢量,保证清晰)
annotations.forEach(a => drawAnnotation(octx, a));
return out;
}
```
Good — redrawing annotations vectorially at full resolution gives crisp results.
Download:
```js
function download(type) {
const out = exportCanvas(type);
out.toBlob(blob => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `screenshot-${timestamp()}.${type === 'image/png' ? 'png' : 'jpg'}`;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}, type, 0.92);
}
```
Copy to clipboard:
```js
async function copyToClipboard() {
const out = exportCanvas('image/png');
const blob = await new Promise(r => out.toBlob(r, 'image/png'));
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
}
```
Note: ClipboardItem may not be supported in Firefox. Wrap in try/catch.
Now the editor modal layout. I'll build it with HTML in the document (hidden by default) and control with JS. Actually, building dynamically is more code; static HTML is clearer. Let's put the editor markup in the HTML and wire it up in JS.
Let me write the HTML/CSS.
Design: dark modern UI, rounded, subtle shadows.
Let me write out the full file now.
```html
网页截图工具 · Web Screenshot Tool
```
Demo content: a hero, some cards, a long article so the page scrolls.
Now, careful with the toolbar being fixed — when capturing "visible window", the toolbar will appear in the screenshot. That's expected/fine (it's a page element). Actually maybe the user wants a clean capture. Hmm — for the demo, having the toolbar visible in the capture is fine and even demonstrates it. But for "整页截图" I hide fixed elements, so the toolbar disappears.
Actually wait: for area selection and visible window, should I hide `[data-capture-ignore]`? For visible-window capture, the toolbar would be in the shot. I think it's better to hide our own UI (the toolbar) for all captures so the result is clean content. But then the user can't see where the button is... it's fine, the capture happens instantly and the toolbar reappears.
Hmm, but hiding the toolbar changes the layout? It's `position: fixed`, so hiding it doesn't affect layout. Good. Let's hide `[data-capture-ignore]` during all captures. But careful: for the area selector overlay, we create it dynamically after capture, so it's not in the frame.
Wait, but there's a timing issue: we hide the toolbar, then grab a frame. The frame must be captured after the re-render. So: hide → await nextFrame + small delay → grab → restore. Good.
Also for the "full page" mode, hide fixed/sticky elements too.
Let me now think about the flow:
```js
async function startCapture(mode) {
try {
setBusy(true);
await Capture.ensureStream(); // triggers permission prompt
...
} catch (err) { toast(err.message); }
}
```
Order matters: for area selection, I want the frame first (to show the frozen background). So:
1. ensureStream
2. hide our UI
3. await delay
4. grabFrame
5. restore UI
6. If mode === 'area': openSelector(frame) → cropped canvas → openEditor
If mode === 'viewport': openEditor(frame)
If mode === 'full': do the scroll-stitch (which itself handles hiding) → openEditor(stitched)
For full page, the frame grabbing loop happens after hiding.
Let me write `Capture.captureFullPage`:
```js
async function captureFullPage(onProgress) {
await ensureStream();
const dpr = video.videoWidth / window.innerWidth; // 近似
const viewportW = window.innerWidth;
const viewportH = window.innerHeight;
const doc = document.documentElement;
const totalH = Math.max(doc.scrollHeight, document.body.scrollHeight, viewportH);
const maxScroll = Math.max(0, totalH - viewportH);
const restore = hideForFullPage();
const positions = [];
for (let y = 0; y < totalH; y += viewportH) positions.push(Math.min(y, maxScroll));
// 去重
const uniq = [...new Set(positions)];
if (uniq[uniq.length-1] !== maxScroll) uniq.push(maxScroll);
const out = document.createElement('canvas');
out.width = Math.round(viewportW * dpr);
out.height = Math.round(totalH * dpr);
const octx = out.getContext('2d');
const originalY = window.scrollY;
for (let i = 0; i < uniq.length; i++) {
onProgress?.(i+1, uniq.length);
window.scrollTo({ top: uniq[i], behavior: 'instant' });
await sleep(160);
const frame = await grabFrame();
const drawY = Math.round(uniq[i] * dpr);
const drawH = Math.min(frame.height, out.height - drawY);
octx.drawImage(frame, 0, 0, frame.width, drawH, 0, drawY, out.width, drawH);
}
window.scrollTo({ top: originalY, behavior: 'instant' });
restore();
return out;
}
```
Wait: `frame.width` might not equal `viewportW * dpr` exactly due to rounding. Let's just scale the frame to `out.width`. Using `octx.drawImage(frame, 0, 0, frame.width, drawH_src, 0, drawY, out.width, drawH_dst)`. Careful with the source crop height when the last frame overflows: we want to draw the portion of the frame from its top, with height = (out.height - drawY) / dpr in CSS px → source height = that * (frame.height / viewportH). Let's compute in CSS px:
```js
const remainingCss = totalH - uniq[i]; // 该帧从顶部起还需要的高度(CSS px)
const srcH = Math.min(frame.height, remainingCss * (frame.height / viewportH));
const dstH = srcH * (out.width / frame.width);
octx.drawImage(frame, 0, 0, frame.width, srcH, 0, drawY, out.width, dstH);
```
Good.
Note: `window.scrollTo({behavior:'instant'})` — 'instant' is valid per spec (ScrollBehavior: auto|instant|smooth). Yes.
Also, `dpr` computed as `video.videoWidth / window.innerWidth` — but if the user captured a different surface (e.g., whole screen), this ratio is meaningless. Then the stitched image would be wrong. I'll add a guard: if the ratio is unreasonable (e.g., <0.5 or >4), warn. Hmm, or just warn in the instructions. I'll add a hint: "整页截图需要选择『当前标签页』".
Actually, let me detect: if `Math.abs(video.videoWidth / video.videoHeight - window.innerWidth / window.innerHeight) > 0.05` → warn that the captured surface aspect doesn't match the tab and full-page may be inaccurate. Just a console warn + toast. Keep it simple, maybe skip.
Hmm, let me include a light check and toast warning but continue.
**Toast**
```js
function toast(msg, type='info', duration=2600) { ... }
```
**Busy indicator** — a small floating pill "正在截取…".
Now let's write the editor markup.
```html
截图编辑
```
CSS for `.canvas-wrap` position relative, canvases stacked absolutely.
Actually, since both canvases are the same size, use:
```css
.canvas-wrap{position:relative; line-height:0; box-shadow:...}
.canvas-wrap canvas{display:block}
#drawCanvas{position:absolute; left:0; top:0; cursor:crosshair}
```
Set both canvases' width/height attributes to the image size and CSS width/height to displaySize.
Now let's handle the modal being scrollable: `.editor-stage { overflow:auto; max-height: 60vh; }`.
OK, let me write the JS now in full.
```js
/* ---------- 小工具 ---------- */
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => Array.from(r.querySelectorAll(s));
const sleep = ms => new Promise(r => setTimeout(r, ms));
const nextPaint = () => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
const clamp = (v, min, max) => Math.min(max, Math.max(min, v));
```
Toast:
```js
let toastTimer;
function toast(msg, type = 'info') {
let el = $('#toast');
if (!el) {
el = document.createElement('div');
el.id = 'toast';
document.body.appendChild(el);
}
el.className = `toast ${type} show`;
el.textContent = msg;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => el.classList.remove('show'), 2800);
}
```
Busy:
```js
function setBusy(on, text = '正在截取…') {
let el = $('#busy');
if (!el) { el = document.createElement('div'); el.id='busy'; el.innerHTML = ''; document.body.appendChild(el); }
el.querySelector('.busy-text').textContent = text;
el.classList.toggle('show', on);
}
```
Capture module:
```js
const Capture = (() => {
let stream = null;
let video = null;
async function ensureStream() {
if (stream && stream.getVideoTracks().some(t => t.readyState === 'live')) return;
if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
throw new Error('当前浏览器不支持屏幕捕获,请使用最新版 Chrome / Edge。');
}
const constraints = {
video: { frameRate: { ideal: 30 }, width: { ideal: 3840 }, height: { ideal: 2160 } },
audio: false,
preferCurrentTab: true,
selfBrowserSurface: 'include',
surfaceSwitching: 'exclude',
systemAudio: 'exclude'
};
stream = await navigator.mediaDevices.getDisplayMedia(constraints);
const track = stream.getVideoTracks()[0];
track.addEventListener('ended', () => { stream = null; if (video) { video.srcObject = null; video = null; } });
video = document.createElement('video');
video.muted = true;
video.playsInline = true;
video.autoplay = true;
video.style.cssText = 'position:fixed;left:-99999px;top:0;width:2px;height:2px;opacity:0;pointer-events:none;';
document.body.appendChild(video);
video.srcObject = stream;
await video.play().catch(() => {});
await new Promise(res => {
if (video.videoWidth) return res();
const t = setTimeout(res, 1500);
video.addEventListener('loadedmetadata', () => { clearTimeout(t); res(); }, { once: true });
});
if (!video.videoWidth) throw new Error('未能获取画面,请重试。');
}
...
})();
```
Wait, appending the video to body: it will be captured if it's on screen — but it's at left:-99999px, so off-screen. OK. But `data-capture-ignore`? Not needed since it's off-screen.
Hmm, one concern: `video.style.width:2px` with opacity 0 — some browsers may throttle rendering of hidden videos? Off-screen videos still play. Fine.
grabFrame as described.
Now the main app:
```js
async function handleCapture(mode) {
if (busy) return;
busy = true;
try {
setBusy(true, mode === 'full' ? '正在截取整页…' : '正在截取…');
await Capture.ensureStream();
let shotCanvas = null;
if (mode === 'area') {
await withHiddenUI(nextPaint);
const frame = await Capture.grabFrame();
await withHiddenUI(); // restore already done
...
}
}
}
```
Hmm, let me structure with a helper:
```js
async function withUIHidden(fn) {
const els = $$('[data-capture-ignore]');
const prev = els.map(el => el.style.visibility);
els.forEach(el => (el.style.visibility = 'hidden'));
try {
await nextPaint();
await sleep(80);
return await fn();
} finally {
els.forEach((el, i) => (el.style.visibility = prev[i]));
}
}
```
Then:
```js
if (mode === 'area') {
const frame = await withUIHidden(() => Capture.grabFrame());
const cropped = await openSelector(frame);
if (cropped) openEditor(cropped);
}
```
But the selector overlay is created after `withUIHidden` restores, so the toolbar will be visible behind the overlay — that's fine (it's behind the frozen screenshot).
For viewport:
```js
const frame = await withUIHidden(() => Capture.grabFrame());
openEditor(frame);
```
For full:
```js
const result = await Capture.captureFullPage((i, n) => setBusy(true, `正在拼接 ${i}/${n}…`));
openEditor(result);
```
And captureFullPage internally hides fixed elements + `[data-capture-ignore]`.
Let me write captureFullPage with the hiding inside.
```js
async function captureFullPage(onProgress) {
await ensureStream();
const vw = window.innerWidth, vh = window.innerHeight;
const totalH = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, vh);
const maxScroll = Math.max(0, totalH - vh);
const startY = window.scrollY;
// 计算缩放比(捕获画面像素 / CSS 像素)
const scale = video.videoWidth / vw;
// 隐藏固定/粘性元素与自身 UI
const restore = hideFixedAndUI();
try {
const out = document.createElement('canvas');
out.width = Math.round(vw * scale);
out.height = Math.round(totalH * scale);
const octx = out.getContext('2d');
octx.fillStyle = '#ffffff';
octx.fillRect(0, 0, out.width, out.height);
const positions = [];
for (let y = 0; y < totalH; y += vh) positions.push(Math.min(y, maxScroll));
if (!positions.includes(maxScroll)) positions.push(maxScroll);
const uniq = [...new Set(positions)].sort((a,b)=>a-b);
for (let i = 0; i < uniq.length; i++) {
onProgress && onProgress(i + 1, uniq.length);
window.scrollTo(0, uniq[i]);
await sleep(180);
const frame = await grabFrame();
const drawY = Math.round(uniq[i] * scale);
const remainCss = Math.min(vh, totalH - uniq[i]);
const srcH = Math.round(remainCss * (frame.height / vh));
const dstH = Math.round(remainCss * scale);
octx.drawImage(frame, 0, 0, frame.width, Math.min(srcH, frame.height), 0, drawY, out.width, Math.min(dstH, out.height - drawY));
}
return out;
} finally {
window.scrollTo(0, startY);
restore();
await nextPaint();
}
}
```
Hmm, the `drawImage` with source/dest sizes — need to be careful they're positive. Let's simplify: always draw the full frame at drawY with height = vh*scale, but clip to the canvas bottom:
```js
const drawH = Math.min(Math.round(vh * scale), out.height - drawY);
octx.drawImage(frame, 0, 0, frame.width, Math.round(drawH / scale * (frame.height / vh)), 0, drawY, out.width, drawH);
```
Simpler: since scale = frame.width/vw and frame.height/vh should be the same ratio (uniform), just do:
```js
const drawH = Math.min(out.height - drawY, Math.round(vh * scale));
const srcH = Math.round(drawH / scale * (frame.height / vh)); // = drawH * frame.height/(vh*scale)
octx.drawImage(frame, 0, 0, frame.width, Math.min(srcH, frame.height), 0, drawY, out.width, drawH);
```
Since frame.height ≈ vh*scale, srcH ≈ drawH. Just use `Math.min(drawH, frame.height)`. Cleaner:
```js
const drawH = Math.min(out.height - drawY, frame.height); // 近似,frame.height ≈ vh*scale
```
But out.width = vw*scale = frame.width, so the horizontal scaling is 1:1. And vertically, frame.height ≈ vh*scale, so drawing at drawY with height frame.height is correct. The only issue is the last frame exceeding the canvas, which drawImage clips automatically! Actually, drawImage with a destination that extends beyond the canvas just clips. So we can simply do:
```js
octx.drawImage(frame, 0, drawY);
```
Wait, but out.width must equal frame.width for 1:1. `out.width = Math.round(vw * scale)` where scale = frame.width/vw → out.width = frame.width.
And out.height = totalH * scale. drawImage(frame, 0, drawY) draws frame.height pixels tall, which for the last frame might exceed the canvas → clipped.
But there's a subtlety: the last frame is captured at scrollY = maxScroll, and its top corresponds to page Y = maxScroll. So drawing it at drawY = maxScroll*scale is correct, and the bottom is clipped at totalH*scale. Since the frame's content below totalH*scale doesn't exist anyway (it's just the viewport bottom = page bottom), it's exactly right.
So simplify: `octx.drawImage(frame, 0, Math.round(uniq[i] * scale))`.
But if frame.width !== out.width due to rounding, use explicit dest size: `octx.drawImage(frame, 0, 0, frame.width, frame.height, 0, drawY, out.width, frame.height * out.width / frame.width)`. Overkill. I'll set out.width = frame.width after the first grab? But I need the canvas before the loop... I can grab the first frame before creating the canvas. Or just compute out.width = Math.round(vw*scale) and accept ±1px. Fine.
Actually, to be safe, let me use `frame.width` for out.width by grabbing the first frame first. Hmm, restructuring. Nah — rounding to ±1px on a 3840px canvas is invisible. Keep simple.
Also: the canvas max size. Browsers limit canvas dimensions (Chrome: max 65535 per side, and max area ~268M pixels). A very long page at scale 2 could exceed. Add a guard: if out.height > 32767 or area > 100M, reduce scale. Let's add:
```js
let scale = video.videoWidth / vw;
const maxPixels = 100 * 1000 * 1000;
const estPixels = vw * scale * totalH * scale;
if (estPixels > maxPixels) scale = scale * Math.sqrt(maxPixels / estPixels);
```
And also cap height at 32000. Let's include a simple adjustment. Good for robustness.
Hmm, but then out.width != frame.width and I'd need scaling in drawImage. Let me handle it properly then:
```js
const drawW = Math.round(vw * scale);
const drawH = Math.round(vh * scale);
octx.drawImage(frame, 0, 0, frame.width, frame.height, 0, Math.round(y*scale), drawW, Math.min(drawH, out.height - Math.round(y*scale)));
```
OK, do it properly with explicit sizes. Let me just write it that way.
Wait, careful: `Math.min(drawH, out.height - drawY)` for dest height, and correspondingly source height should be scaled: `srcH = frame.height * (destH / drawH)`. Let me write:
```js
const dy = Math.round(y * scale);
const dh = Math.min(drawH, out.height - dy);
if (dh <= 0) continue;
const sh = frame.height * (dh / drawH);
octx.drawImage(frame, 0, 0, frame.width, sh, 0, dy, drawW, dh);
```
Good.
Now `hideFixedAndUI`:
```js
function hideFixedAndUI() {
const changed = [];
const mark = (el, prop, val) => { changed.push([el, prop, el.style[prop]]); el.style[prop] = val; };
$$('[data-capture-ignore]').forEach(el => mark(el, 'visibility', 'hidden'));
$$('body *').forEach(el => {
if (el.closest('[data-capture-ignore]')) return;
const cs = getComputedStyle(el);
if (cs.position === 'fixed' || cs.position === 'sticky') {
mark(el, 'visibility', 'hidden');
}
});
return () => changed.forEach(([el, prop, val]) => { el.style[prop] = val; });
}
```
Note: getComputedStyle for every element is expensive on big pages but OK for a demo.
Hmm, one issue: `el.style.visibility` — if the original was set via a class, restoring `el.style.visibility = ''` is correct (we saved the inline value which is likely '').
Also, for sticky elements, hiding them may remove content that only appears at the top. Acceptable; and I'll add a checkbox in the toolbar "整页隐藏固定元素" default checked. Hmm, adding a checkbox complicates. Let me just do it by default and mention it.
Actually, let me make it a toggle in the toolbar settings area. Keep it simple: I'll add a checkbox in the toolbar. Hmm, the toolbar has 3 buttons. Adding a checkbox row is fine.
Let me keep the toolbar minimal: three buttons + a small hint line. And a checkbox "整页隐藏固定元素". OK.
Now the selector overlay.
```js
function openSelector(frame) {
return new Promise(resolve => {
const vw = window.innerWidth, vh = window.innerHeight;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const wrap = document.createElement('div');
wrap.className = 'shot-overlay';
wrap.innerHTML = `
按住鼠标拖动框选截图区域 · Enter 确认 · Esc 取消
`;
document.body.appendChild(wrap);
const base = wrap.querySelector('.shot-base');
const mask = wrap.querySelector('.shot-mask');
const bar = wrap.querySelector('.shot-bar');
const sizeLabel = wrap.querySelector('.shot-size');
const fit = Math.min(vw / frame.width, vh / frame.height);
const dw = frame.width * fit, dh = frame.height * fit;
const dx = (vw - dw) / 2, dy = (vh - dh) / 2;
for (const c of [base, mask]) {
c.width = Math.round(vw * dpr);
c.height = Math.round(vh * dpr);
c.style.width = vw + 'px';
c.style.height = vh + 'px';
}
const bctx = base.getContext('2d');
bctx.setTransform(dpr, 0, 0, dpr, 0, 0);
bctx.fillStyle = '#05070b';
bctx.fillRect(0, 0, vw, vh);
bctx.imageSmoothingQuality = 'high';
bctx.drawImage(frame, dx, dy, dw, dh);
const mctx = mask.getContext('2d');
let sel = null, dragging = false, startPt = null;
function draw() {
mctx.setTransform(dpr, 0, 0, dpr, 0, 0);
mctx.clearRect(0, 0, vw, vh);
mctx.fillStyle = 'rgba(5,7,11,.62)';
mctx.fillRect(0, 0, vw, vh);
if (sel && sel.w > 1 && sel.h > 1) {
mctx.clearRect(sel.x, sel.y, sel.w, sel.h);
mctx.strokeStyle = '#4c8dff';
mctx.lineWidth = 1.5;
mctx.strokeRect(sel.x + .75, sel.y + .75, sel.w - 1.5, sel.h - 1.5);
// 四角
...
// 尺寸提示
const label = `${Math.round(sel.w / fit)} × ${Math.round(sel.h / fit)}`;
mctx.font = '600 12px ...';
...
}
}
...
});
}
```
For the size label, drawing text on the mask canvas is fine. But we also have the `.shot-size` span in the bar. Let's use both: draw near the rect and also show in the bar.
Let me keep it simpler: draw the label above the selection rect on the mask canvas.
Mouse events: attach mousedown to `wrap`, mousemove/mouseup to window.
```js
function toLocal(e) { return { x: e.clientX, y: e.clientY }; } // overlay covers the viewport at (0,0)
function clampToImage(p) {
return { x: clamp(p.x, dx, dx + dw), y: clamp(p.y, dy, dy + dh) };
}
function onDown(e) {
if (e.target.closest('.shot-bar')) return;
const p = clampToImage(toLocal(e));
dragging = true;
startPt = p;
sel = { x: p.x, y: p.y, w: 0, h: 0 };
bar.hidden = true;
draw();
}
function onMove(e) {
if (!dragging) return;
const p = clampToImage(toLocal(e));
sel = {
x: Math.min(startPt.x, p.x),
y: Math.min(startPt.y, p.y),
w: Math.abs(p.x - startPt.x),
h: Math.abs(p.y - startPt.y)
};
draw();
}
function onUp() {
if (!dragging) return;
dragging = false;
if (sel && sel.w > 8 && sel.h > 8) {
bar.hidden = false;
sizeLabel.textContent = `${Math.round(sel.w / fit)} × ${Math.round(sel.h / fit)} px`;
// 把操作条移动到选区下方
const barW = 320;
let left = clamp(sel.x + sel.w / 2 - barW/2, 12, vw - barW - 12);
let top = sel.y + sel.h + 14;
if (top + 52 > vh) top = Math.max(12, sel.y - 62);
bar.style.left = left + 'px';
bar.style.top = top + 'px';
} else {
sel = null;
draw();
}
}
```
The bar's width is dynamic; using a fixed 320 estimate is OK-ish. Better: after showing, measure `bar.offsetWidth`. Let's do: `bar.hidden = false; const bw = bar.offsetWidth; ...`.
Confirm handler:
```js
function confirm() {
if (!sel) return;
const sx = (sel.x - dx) / fit;
const sy = (sel.y - dy) / fit;
const sw = sel.w / fit;
const sh = sel.h / fit;
const out = document.createElement('canvas');
out.width = Math.max(1, Math.round(sw));
out.height = Math.max(1, Math.round(sh));
const octx = out.getContext('2d');
octx.drawImage(frame, Math.round(sx), Math.round(sy), Math.round(sw), Math.round(sh), 0, 0, out.width, out.height);
cleanup();
resolve(out);
}
```
Key handlers: Enter → confirm (if sel), Esc → cancel.
Also allow a full-image default: if no selection and user presses Enter, use the whole frame? Nah.
Cleanup: remove wrap, remove listeners.
**Editor module**
```js
const Editor = (() => {
const modal = $('#editorModal');
const stage = $('#editorStage');
const baseCanvas = $('#baseCanvas');
const drawCanvas = $('#drawCanvas');
const bctx = baseCanvas.getContext('2d');
const dctx = drawCanvas.getContext('2d');
let image = null; // 原始截图 canvas
let annotations = [];
let redoStack = [];
let current = null;
let tool = 'rect';
let color = '#ff3b30';
let lineWidth = 3;
let displayScale = 1;
let activeInput = null;
let drawing = false;
let startPoint = null;
function open(shotCanvas) {
image = shotCanvas;
annotations = [];
redoStack = [];
current = null;
const maxW = Math.max(320, window.innerWidth * 0.86);
const maxH = Math.max(240, window.innerHeight * 0.62);
displayScale = Math.min(1, maxW / image.width, maxH / image.height);
const w = Math.round(image.width * displayScale);
const h = Math.round(image.height * displayScale);
for (const c of [baseCanvas, drawCanvas]) {
c.width = image.width;
c.height = image.height;
c.style.width = w + 'px';
c.style.height = h + 'px';
}
bctx.clearRect(0,0,image.width,image.height);
bctx.drawImage(image, 0, 0);
render();
$('#imgInfo').textContent = `${image.width} × ${image.height} px`;
modal.hidden = false;
document.body.style.overflow = 'hidden';
}
function close() { ... }
...
})();
```
Wait: setting `document.body.style.overflow = 'hidden'` while the page might need scrolling... it's fine.
Mouse events on drawCanvas:
```js
drawCanvas.addEventListener('pointerdown', e => {
if (e.button !== 0) return;
const p = toImage(e);
if (tool === 'text') { startTextInput(p); return; }
drawing = true;
drawCanvas.setPointerCapture(e.pointerId);
startPoint = p;
if (tool === 'rect') current = { type:'rect', x:p.x, y:p.y, w:0, h:0, color, lineWidth: lw() };
else if (tool === 'arrow') current = { type:'arrow', x1:p.x, y1:p.y, x2:p.x, y2:p.y, color, lineWidth: lw() };
else if (tool === 'pen') current = { type:'pen', points:[p], color, lineWidth: lw() };
render();
});
```
`lw()` = lineWidth / displayScale.
pointermove:
```js
if (!drawing || !current) return;
const p = toImage(e);
if (current.type === 'rect') { current.w = p.x - current.x; current.h = p.y - current.y; }
else if (current.type === 'arrow') { current.x2 = p.x; current.y2 = p.y; }
else if (current.type === 'pen') { current.points.push(p); }
render();
```
pointerup:
```js
if (!drawing) return;
drawing = false;
if (current) {
// 过滤过小的图形
const ok = current.type === 'rect' ? (Math.abs(current.w) > 3 && Math.abs(current.h) > 3)
: current.type === 'arrow' ? (Math.hypot(current.x2-current.x1, current.y2-current.y1) > 5)
: current.points.length > 1;
if (ok) { annotations.push(current); redoStack = []; }
current = null;
}
render();
```
Rect normalization for drawing: handle negative w/h in the draw function:
```js
const x = a.w < 0 ? a.x + a.w : a.x;
const y = a.h < 0 ? a.y + a.h : a.y;
const w = Math.abs(a.w), h = Math.abs(a.h);
```
render():
```js
function render() {
dctx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);
for (const a of annotations) drawAnnotation(dctx, a);
if (current) drawAnnotation(dctx, current);
}
```
drawAnnotation(ctx, a):
```js
function drawAnnotation(ctx, a) {
ctx.save();
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = a.color;
ctx.fillStyle = a.color;
ctx.lineWidth = a.lineWidth;
if (a.type === 'rect') {
const x = a.w < 0 ? a.x + a.w : a.x;
const y = a.h < 0 ? a.y + a.h : a.y;
ctx.strokeRect(x, y, Math.abs(a.w), Math.abs(a.h));
} else if (a.type === 'arrow') {
drawArrow(ctx, a);
} else if (a.type === 'pen') {
ctx.beginPath();
a.points.forEach((p, i) => i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y));
ctx.stroke();
} else if (a.type === 'text') {
ctx.font = `700 ${a.fontSize}px -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif`;
ctx.textBaseline = 'top';
ctx.shadowColor = 'rgba(0,0,0,.45)';
ctx.shadowBlur = a.fontSize * 0.25;
ctx.fillText(a.text, a.x, a.y);
}
ctx.restore();
}
```
Hmm, shadowBlur on text at large sizes could be slow but fine.
For text with multi-line? Keep single line.
drawArrow as before.
**Text input overlay**
```js
function startTextInput(p) {
commitTextInput();
const input = document.createElement('input');
input.type = 'text';
input.className = 'text-input';
input.placeholder = '输入文字…';
const cssX = p.x * displayScale;
const cssY = p.y * displayScale;
input.style.left = cssX + 'px';
input.style.top = cssY + 'px';
input.style.color = color;
input.style.fontSize = Math.max(12, lineWidth * 6) + 'px'; // hmm
...
}
```
Hmm, font size for text: I should have a separate control. Let me reuse the line width slider as a "size" for text? That's confusing. Let me add a separate font size slider shown only when the text tool is active. Or simpler: use a fixed font size derived from the image width, e.g., `fontSize = Math.round(image.width / 40)` clamped. Hmm, users want control.
Let me add a font-size range input that appears when the text tool is selected. Actually simpler: reuse the same slider but label it dynamically ("线宽" / "字号"). That's elegant: when tool==='text', the slider label becomes "字号" and the value range is larger (min 12 max 72). Let me just have two sliders and toggle visibility. Hmm.
I'll do the dynamic label approach with two ranges:
- `#lineWidth` (1-16) for shapes
- `#fontSize` (12-72) for text
Toggle which one is displayed based on the tool.
OK, that's clean.
Text input position: the input is placed inside `#canvasWrap` (position relative) at the click point. Font size in CSS px = fontSize (the UI value). Since the canvas is displayed at displayScale, a font of size F in image px appears as F*displayScale CSS px. So for the input to match visually, `input.style.fontSize = (F * displayScale) + 'px'`. And the annotation stores `fontSize: F / displayScale`...
Wait, let me redo: I want the text to appear at a certain visual size. Let the UI font size be `uiFont` (in CSS px at the current display). Then in image pixels, `fontSize = uiFont / displayScale`. And the input's CSS font-size = uiFont. And the annotation's fontSize (image px) = uiFont / displayScale. On render at displayScale, it appears as uiFont. Correct.
Same for line width: `lineWidth = uiWidth / displayScale` in image px.
Good, consistent.
Now, the input: on Enter or blur → commit:
```js
function commitTextInput() {
if (!activeInput) return;
const { input, point } = activeInput;
const text = input.value.trim();
input.remove();
activeInput = null;
if (text) {
annotations.push({ type:'text', x: point.x, y: point.y, text, color: input.dataset.color, fontSize: parseFloat(input.dataset.fontSize) });
redoStack = [];
render();
}
}
```
Careful with pointerdown on the canvas while the input is open: the pointerdown handler calls `startTextInput` which first commits the previous. But the blur event will also fire and commit. Guard with the `activeInput` null check — after commit, activeInput is null so the blur handler does nothing. But order: mousedown on canvas → blur fires first (before mousedown handler? Actually blur fires on mousedown, before the mouseup/click). Sequence: mousedown on canvas → the input loses focus → blur → commit. Then our pointerdown handler runs → startTextInput → creates a new input. Since commit set activeInput=null, fine.
Also, `input.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); commitTextInput(); } if (e.key === 'Escape') { input.value=''; commitTextInput(); } })`.
Need to focus the input after appending: `requestAnimationFrame(() => input.focus())`.
Note: Escape inside the editor also closes the modal — need to check `activeInput` in the global key handler.
**Undo/redo/clear**
```js
function undo() { const a = annotations.pop(); if (a) { redoStack.push(a); render(); } }
function redo() { const a = redoStack.pop(); if (a) { annotations.push(a); render(); } }
function clearAll() { if (!annotations.length) return; redoStack = []; annotations = []; render(); }
```
Hmm, for clearAll, ideally undoable. Let's push all to a history. Simple approach: keep `annotations` and a history stack of snapshots. Let me use snapshots — simpler and correct:
```js
let history = []; // 快照数组
let historyIndex = -1;
function snapshot() {
history = history.slice(0, historyIndex + 1);
history.push(JSON.parse(JSON.stringify(annotations)));
historyIndex = history.length - 1;
updateHistoryButtons();
}
function undo() { if (historyIndex > 0) { historyIndex--; annotations = clone(history[historyIndex]); render(); } }
function redo() { if (historyIndex < history.length - 1) { historyIndex++; annotations = clone(history[historyIndex]); render(); } }
```
Initialize with `snapshot()` on open (empty array). After each committed annotation, `snapshot()`. Clear → annotations = []; snapshot(). This handles everything uniformly.
JSON clone of pen points could be heavy but fine.
**Export & download**
```js
function exportCanvas(type) {
const out = document.createElement('canvas');
out.width = image.width; out.height = image.height;
const octx = out.getContext('2d');
if (type === 'image/jpeg') { octx.fillStyle = '#fff'; octx.fillRect(0,0,out.width,out.height); }
octx.drawImage(image, 0, 0);
annotations.forEach(a => drawAnnotation(octx, a));
return out;
}
```
Download with a filename including a timestamp.
Copy to clipboard with ClipboardItem, wrapped in try/catch and a fallback message.
**Global keyboard**
```js
document.addEventListener('keydown', e => {
if (!modal.hidden) {
const mod = e.ctrlKey || e.metaKey;
if (mod && e.key.toLowerCase() === 'z') { e.preventDefault(); e.shiftKey ? redo() : undo(); }
else if (mod && e.key.toLowerCase() === 's') { e.preventDefault(); download(); }
else if (e.key === 'Escape' && !activeInput) { close(); }
}
});
```
But this listener should be added inside the Editor module. And the selector overlay has its own key handling — need to avoid conflicts. The selector is only open when the editor is closed, so fine.
Alright. Also, the editor modal should have a mask that closes on click? Risky for accidental loss. I'll make the mask click close it, with the annotations lost — maybe ask for confirmation? Just close (no confirm) is fine, but let's not close on mask click to avoid accidents. I'll keep the ✕ button and Esc.
Now let's write the CSS for everything. I'll write a decent-looking dark theme.
Let me also make sure the demo page has enough content to scroll for the full-page test.
Let me write the final code.
One more consideration: `getDisplayMedia` requires a user gesture and secure context (https or localhost). If opened via file://, `navigator.mediaDevices` is undefined! That's a big deal for "executable demo". Opening an HTML file directly with file:// → `navigator.mediaDevices` is undefined in Chrome (not a secure context). Hmm. Actually, file:// URLs... Chrome treats file:// as a secure context? Let me recall: `window.isSecureContext` for file:// is true in Chrome. Yes! Chrome considers file:// origins as potentially trustworthy → isSecureContext === true. But `navigator.mediaDevices` might still be undefined... I believe on file:// Chrome does expose mediaDevices. Hmm, actually there have been issues. Firefox also treats file:// as secure? Firefox: file:// is a secure context, yes.
I'll add a graceful error message if `navigator.mediaDevices?.getDisplayMedia` is missing, telling the user to serve over http://localhost or https.
Also add a note in the UI about this.
Alternative fallback: if getDisplayMedia is unavailable, we could fall back to html2canvas for DOM capture. That's extra. I'll just show the error message.
Let me now also double check: the user asks "capture browser areas through simple button triggers". getDisplayMedia is the right API.
Let me write everything out now.
CSS details:
```css
.btn {
appearance: none; border: 1px solid transparent; border-radius: 9px;
padding: 8px 14px; font-size: 13px; font-weight: 600; cursor: pointer;
background: var(--panel-2); color: var(--text); transition: .18s;
font-family: inherit;
}
.btn:hover { background: #263040; }
.btn.primary { background: linear-gradient(180deg,#5b97ff,#3b7bff); color:#fff; box-shadow:0 4px 14px rgba(59,123,255,.35); }
.btn.primary:hover { filter: brightness(1.08); }
.btn.ghost { background: transparent; border-color: var(--line); color: var(--muted); }
.btn.ghost:hover { color: var(--text); border-color: #3b4757; background: rgba(255,255,255,.04); }
```
Toolbar:
```css
.toolbar {
position: fixed; right: 20px; top: 20px; z-index: 1000;
width: 260px; background: rgba(22,27,34,.92); backdrop-filter: blur(14px);
border: 1px solid var(--line); border-radius: 16px; padding: 14px;
box-shadow: 0 18px 50px rgba(0,0,0,.45);
}
```
Inside: title, 3 buttons stacked, hint text, checkbox.
Actually, let's make the buttons a row of 3 with icons and labels beneath. A 260px panel with 3 stacked full-width buttons is cleanest.
Now writing the demo content: a hero with a title, a few feature cards, an article with paragraphs, a "long" section so the page scrolls a lot.
Let me write it.
```html
网页截图工具
点击右上角的按钮,即可截取 框选区域、当前可视窗口 或 整个网页,并直接在浏览器里完成标注与保存。
▭
区域截图
自由框选任意矩形范围,精确到像素。
▣
可视窗口
一键截取当前屏幕中可见的全部内容。
▤
整页长截图
自动滚动拼接,把整篇长文一次拿下。
使用说明
...
...
```
I'll add enough content for scrolling.
Let me be careful that the demo content doesn't overlap the fixed toolbar on the right. Add `padding-right` on the page for large screens? The toolbar is at right:20px, width 260px. The page content max-width 1000px centered — could overlap on narrow screens. Add `@media (max-width: 1100px)` to reduce. Or just place the toolbar at the top-right and give the page `padding-right: 300px` on wide screens. Let's do: `.page { max-width: 980px; margin: 0 auto; padding: 60px 24px 120px; }` and the toolbar floats over. On a 1400px screen, the content is 980px centered → left edge at 210, right edge at 1190, toolbar starts at 1400-280=1120. Overlap! Let me add `@media (min-width: 1280px) { .page { margin-right: 320px; margin-left: auto; } }`. Hmm, that's asymmetric. Alternatively, make the page `max-width: 900px; margin-left: 8%; margin-right: auto` — meh.
Simplest: keep the page centered but add `padding-right` to the body... Let's just use:
```css
.page { width: min(920px, 100% - 340px); margin: 0 auto; padding: 56px 0 120px; }
```
Hmm, `100% - 340px` — calc needed: `width: min(920px, calc(100% - 340px))`. On narrow screens this becomes tiny. Use media query:
```css
.page{max-width:920px;margin:0 auto;padding:56px 24px 140px;}
@media (min-width:1280px){
.page{max-width:920px;margin:0 0 0 6vw;}
}
```
That puts content on the left and the toolbar on the right. Clean. Let's do that.
Actually simpler: put the toolbar at top-right and the content with `padding-right` in the body for wide screens. I'll go with the media query approach.
Now, let me finalize and write the whole thing.
One more thing about `nextPaint` — it uses requestAnimationFrame twice. Fine.
Also, the hidden UI restore must happen even if an error occurs — using try/finally.
Let me write `handleCapture`:
```js
let capturing = false;
async function handleCapture(mode) {
if (capturing) return;
capturing = true;
try {
setBusy(true, '正在准备截图…');
await Capture.ensureStream();
await nextPaint();
if (mode === 'area') {
const frame = await withUIHidden(() => Capture.grabFrame());
setBusy(false);
const cropped = await openSelector(frame);
if (cropped) openEditor(cropped);
} else if (mode === 'viewport') {
const frame = await withUIHidden(() => Capture.grabFrame());
setBusy(false);
openEditor(frame);
} else {
const stitched = await Capture.captureFullPage((i, n) => setBusy(true, `正在拼接第 ${i}/${n} 屏…`));
setBusy(false);
openEditor(stitched);
}
} catch (err) {
console.error(err);
if (err && err.name === 'NotAllowedError') toast('已取消屏幕捕获授权', 'warn');
else toast(err.message || '截图失败,请重试', 'error');
} finally {
setBusy(false);
capturing = false;
}
}
```
Note: `withUIHidden` restores the UI before returning the frame. Good.
But wait: for the 'area' mode, after grabbing the frame we show the overlay — but the frame is from before... the overlay covers everything anyway.
Hmm, one issue with the area mode: the user sees the frozen screenshot with the toolbar visible in it (since the frame was captured with the UI hidden, actually no — the UI was hidden during the grab, so the toolbar is NOT in the frame). Good.
Now `openEditor` — I'll expose `Editor.open(canvas)`.
Also `openSelector` returns a promise resolving to the cropped canvas or null.
Let me also add a "重新截图" button in the editor? Not necessary.
Now writing everything.
For `Capture.ensureStream`, note that `getDisplayMedia` constraints with `preferCurrentTab` etc. are non-standard but harmless in other browsers.
Let me write the final code.
Also add: after the stream ends (user clicks "Stop sharing"), we should clear it. Handled by the 'ended' listener.
Let me write the whole file now, carefully.
```js
/* ============================================================
* 1. 通用工具
* ============================================================ */
```
I'll write it all in one `
```
### Three Capture Modes, One Editing Canvas
Here's how the main pieces fit together so you can start capturing in seconds.
- **Top-right control panel** – The fixed toolbar holds the three capture buttons and a checkbox. Choosing "框选区域" opens a full-screen overlay where you drag to select any rectangular region; "当前可视窗口" instantly grabs the visible viewport; "整个网页(长截图)" auto-scrolls and stitches the full page. The checkbox decides whether fixed/sticky elements are hidden during full-page capture.
- **Built-in annotation editor** – After any capture, a modal opens with four tools: rectangle, arrow, pen, and text. You can pick from six colors, adjust line width (or font size for text), and use undo/redo or clear-all. Text annotations are placed by clicking directly on the image.
- **Save and share** – The bottom bar shows the image dimensions, a format selector (PNG or JPEG), a "复制" button for the clipboard, and a "保存图片" button that downloads the edited screenshot with a timestamped filename.