Screenuo.com
Screenuo.com Β· Developer Course & Documentation

Widget Architecture & Line-by-Line Code Guide

Learn how to embed, customize, and master Screenuo’s interactive screenshot and annotation engineβ€”from beginner setup to advanced canvas memory optimization.

Beginner Track

Step-by-Step: How to Embed & Use the Widget

Follow these four simple steps to add full-page capture and visual annotation to any website.

1

Add the HTML Container

Place an empty <div id="screenuo-widget" data-key="YOUR_KEY"></div> anywhere on your page and load embed.js asynchronously.

2

Automatic Domain Handshake

On load, the script validates your data-key and window.location.hostname via widget_config.php and applies your button color and permissions.

3

1-Click Cloud Capture

Clicking Capture calls executeCapture(), queues a background render job, and polls /URL/status/ with a live 0%–100% progress badge.

4

Annotate, Share & Restore

Tap the screenshot to launch the vector editor. Add text, numbered pins, shapes, or overlays, then save a shareable ?scn_edit=... link.

Minimal HTML Integration Example
<div id="screenuo-widget" data-key="YOUR_WIDGET_KEY"></div>
<script src="https://screenuo.com/embed.js" async></script>
Advanced Track

Deep Dive: GPU Rendering, Memory Safety & JS API

Under-the-hood engineering techniques used in embed.js for 60 FPS mobile performance and external app integration.

A

Preventing 5K Mobile Crashes

Uncompressed 5K bitmaps consume ~60–100 MB RAM per canvas. getMaxWorkingSide() caps mobile working canvases at 1920px and releaseEditorMemory() frees buffers on save.

B

Dual-Canvas & Path Bitmap Cache

The clean base image lives in an offscreen baseOffscreen canvas (alpha: false). Freehand strokes are cached via getOrBuildPathCache() and batched with requestAnimationFrame.

C

Viewport Matrix Pinch-to-Zoom

Zoom uses edCtx.setTransform(viewZoom, 0, 0, viewZoom, viewPanX, viewPanY) instead of blurry CSS scaling, while clientToCanvasPoint() maps touch gestures into vector space.

D

Host JS API & Events

Control the widget programmatically via window.Screenuo.capture(url) or Screenuo.loadEdit(stateUrl), and listen to window.addEventListener('screenuo:captured', ...).

Line-by-Line Reference

Complete Code Breakdown (embed.js)

Search any function, state variable, or canvas pipeline stage below.

1. IIFE Scope, API Endpoints & Mobile Memory Cap Lines 1 – 22
(function () { const CONTAINER_ID = 'screenuo-widget'; const CONFIG_API = 'https://screenuo.com/api/widget_config.php'; const CAPTURE_API = 'https://screenuo.com/api/widget_capture.php'; const SAVE_EDIT_API = 'https://screenuo.com/api/widget_save_edit.php'; const STATUS_API = 'https://screenuo.com/URL/status/'; const UPLOADS_BASE = 'https://screenuo.com/URL/uploads/'; const DOC_URL = 'https://screenuo.com/doc.html';
Lines 1–8 Isolated IIFE & Backend Endpoints Wraps the entire widget in an Immediately Invoked Function Expression so global variables never clash with host websites, and defines all REST endpoints.
const container = document.getElementById(CONTAINER_ID); if (!container) return; const widgetKey = container.getAttribute('data-key'); if (!widgetKey) return; const STORAGE_KEY = `scn_history_${widgetKey}`;
Lines 10–15 Container & Widget Key Binding Locates the target #screenuo-widget element, extracts its data-key attribute, and creates a scoped localStorage key for version history.
function getMaxWorkingSide() { const isMobileLike = (navigator.maxTouchPoints > 0) || (window.innerWidth <= 1024); return isMobileLike ? 1920 : 3200; }
Lines 18–21 Adaptive Canvas Resolution Limiter Detects touchscreens or viewports ≤ 1024px and caps the working canvas at 1920px so 5K captures never trigger mobile out-of-memory browser crashes.
2. Browser History Cache & Host Event Bridge Lines 255 – 305
function readLocalHistory() { try { const raw = localStorage.getItem(STORAGE_KEY); const arr = JSON.parse(raw || '[]'); return Array.isArray(arr) ? arr : []; } catch (_) { return []; } }
Lines 257–264 Safe History Retrieval Parses previously saved edits from localStorage inside a try/catch guard so private browsing modes never throw storage exceptions.
function saveToLocalHistory(entry) { const list = readLocalHistory(); const filtered = list.filter(item => item.image_url !== entry.image_url); filtered.unshift({ id: 'h_' + Date.now(), timestamp: Date.now(), ...entry }); localStorage.setItem(STORAGE_KEY, JSON.stringify(filtered.slice(0, 10))); }
Lines 266–280 Deduplicated Version Persistence Prepends the newest capture or edited state (including its editable JSON snapshot) and retains the 10 most recent versions in browser cache.
function emitResult(sourceUrl, imageUrl, stateUrl = null) { const payload = { source_url: sourceUrl, image_url: imageUrl, state_url: stateUrl }; window.dispatchEvent(new CustomEvent('screenuo:captured', { detail: payload })); window.postMessage({ type: 'screenuo:captured', ...payload }, '*'); return payload; }
Lines 289–299 Parent Page Event Emitter Publishes image_url and state_url via both a DOM CustomEvent and postMessage for seamless CMS or e-commerce integration.
3. Dual-Canvas GPU Blitting, Viewport Zoom & 60 FPS Scheduler Lines 520 – 760
const edCtx = edCanvas.getContext('2d', { alpha: false }); const baseOffscreen = document.createElement('canvas'); const baseOffCtx = baseOffscreen.getContext('2d', { alpha: false });
Lines 532–558 Opaque Offscreen Backing Canvas Disabling the alpha channel ({ alpha: false }) lets the browser composite frames directly on the GPU, blitting baseOffscreen instead of slow CPU putImageData calls.
function clientToCanvasPoint(clientX, clientY) { const rect = edCanvas.getBoundingClientRect(); const screenX = (clientX - rect.left) * (edCanvas.width / Math.max(1, rect.width)); const screenY = (clientY - rect.top) * (edCanvas.height / Math.max(1, rect.height)); return { x: (screenX - viewPanX) / viewZoom, y: (screenY - viewPanY) / viewZoom }; }
Lines 698–707 Inverse Viewport Coordinate Mapping Translates raw screen touch or mouse coordinates into unzoomed logical canvas coordinates regardless of current viewZoom and pan offsets.
function scheduleRedraw(showSelection = true) { rafShowSelection = showSelection; if (rafPending) return; rafPending = true; requestAnimationFrame(() => { rafPending = false; redrawImmediate(rafShowSelection); }); }
Lines 778–787 Frame-Coalesced Render Loop Throttles high-frequency touchmove and pointermove events to the display refresh rate via requestAnimationFrame.
4. Vector Layers (Pins, Transparent Text, Shapes) & JSON Serialization Lines 1015 – 1620
function drawPinLayer(ctx, layer, pinNumber, totalPins) { const isFinalGreen = (totalPins > 1 && pinNumber === totalPins); const fillColor = isFinalGreen ? '#539c57' : (layer.color || '#0284c7'); ... }
Lines 1320–1365 Auto-Numbered Route Pins Renders teardrop pins numbered sequentially from 1. When multiple pins are present, the final destination pin switches to green (#539c57) with an inner white circle.
function openTextInputAt(cx, cy, boxX, boxY, editIdx = -1) { const wrap = document.createElement('div'); wrap.className = 'scn-ed-text-box'; const area = document.createElement('textarea'); ... }
Lines 1545–1670 Transparent Resizable Text Box Creates a 1-line initial transparent <textarea> with a 1px border and side/corner drag handles. Flexbox centering keeps text centered vertically and horizontally as the box expands.
function serializeProjectState() { return { version: 2, source_url: lastSourceUrl, clean_base_url: cleanBaseImageUrl, canvas_width: edCanvas.width, canvas_height: edCanvas.height, crop: { ...cropOffset }, layers: serializedLayers }; }
Lines 1075–1115 Portable JSON Project Export Serializes all layers, custom layer names, fonts, alignments, crop coordinates, and embedded images into a standalone .json file for shared re-editing.
5. Unified Pointer Events & Chunked Upload Progress Lines 1720 – 2080
edCanvas.addEventListener('pointerdown', onPointerDown); edCanvas.addEventListener('pointermove', onPointerMove); edCanvas.addEventListener('pointerup', onPointerUp);
Lines 1975–1982 Capacitive, Resistive & Stylus Support Uses W3C Pointer Events with setPointerCapture and a 5px jitter deadzone so resistive touchscreens, styluses, and fingers work reliably without accidental drags.
edCanvas.toBlob(async (blob) => { const xhr = new XMLHttpRequest(); xhr.open('POST', SAVE_EDIT_API, true); xhr.upload.onprogress = (ev) => { ... }; }, 'image/jpeg', 0.88);
Lines 2020–2085 Real-Time Upload Progress & Memory Cleanup Encodes the flattened canvas to JPEG, streams both the image and project_json via XMLHttpRequest with live 0%–100% progress, and releases canvas buffers afterward.