Skip to content

The headless browser for AI agents and web scraping

Paint live Canvas2D backing surfaces

SGavrlc35db679c012
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 47a63fee..60f27144 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -5254,6 +5254,7 @@ function _elementClassFor(nid) {
const tag = _domParse("tag_name", nid);
if (tag === "FORM" && globalThis.HTMLFormElement) return globalThis.HTMLFormElement;
if (tag === "IMG") return HTMLImageElement;
+ if (tag === "CANVAS" && globalThis.HTMLCanvasElement) return globalThis.HTMLCanvasElement;
if (tag === "AUDIO") return HTMLAudioElement;
if (tag === "VIDEO") return HTMLVideoElement;
if (tag === "TRACK") return HTMLTrackElement;
@@ -10141,15 +10142,15 @@ class _IframeWindow {
// per session (from _fpNoise) and valid, so it does not match the known
// headless stub.
function _encodePNG(w, h, rgba) {
- // RGB scanlines: filter byte (0) + 3 bytes per pixel
- var rowLen = 1 + w * 3;
+ // RGBA scanlines: filter byte (0) + 4 bytes per pixel.
+ var rowLen = 1 + w * 4;
var raw = new Uint8Array(h * rowLen);
for (var y = 0; y < h; y++) {
var base = y * rowLen;
raw[base] = 0;
for (var x = 0; x < w; x++) {
- var s = (y * w + x) << 2, d = base + 1 + x * 3;
- raw[d] = rgba[s]; raw[d+1] = rgba[s+1]; raw[d+2] = rgba[s+2];
+ var s = (y * w + x) << 2, d = base + 1 + x * 4;
+ raw[d] = rgba[s]; raw[d+1] = rgba[s+1]; raw[d+2] = rgba[s+2]; raw[d+3] = rgba[s+3];
}
}
// Adler32 of raw
@@ -10189,7 +10190,7 @@ function _encodePNG(w, h, rgba) {
var ihd = new Uint8Array(13);
ihd[0]=(w>>24)&0xff; ihd[1]=(w>>16)&0xff; ihd[2]=(w>>8)&0xff; ihd[3]=w&0xff;
ihd[4]=(h>>24)&0xff; ihd[5]=(h>>16)&0xff; ihd[6]=(h>>8)&0xff; ihd[7]=h&0xff;
- ihd[8]=8; ihd[9]=2; // 8-bit RGB
+ ihd[8]=8; ihd[9]=6; // 8-bit RGBA
var png = new Uint8Array(8 + 25 + (12+dlen) + 12);
png.set([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A]);
var p = 8;
@@ -10208,18 +10209,21 @@ function _encodePNG(w, h, rgba) {
globalThis.__ariaQuerySelector = function(root, selector) { return null; };
globalThis.__ariaQuerySelectorAll = async function*(root, selector) { /* yields nothing */ };
+const _MAX_CANVAS_DIMENSION = 32767;
+const _MAX_CANVAS_PIXELS = 67108864;
class _Canvas2D {
constructor(canvas) {
this.canvas = canvas;
- this._w = parseInt(canvas.getAttribute('width')) || 300;
- this._h = parseInt(canvas.getAttribute('height')) || 150;
- this._buf = new Uint8ClampedArray(this._w * this._h * 4);
- for (let i = 0; i < this._w * this._h; i++) {
- this._buf[i*4+0] = 255 + Math.floor(_fpNoise(i % this._w, Math.floor(i / this._w), 0));
- this._buf[i*4+1] = 255 + Math.floor(_fpNoise(i % this._w, Math.floor(i / this._w), 1));
- this._buf[i*4+2] = 255 + Math.floor(_fpNoise(i % this._w, Math.floor(i / this._w), 2));
- this._buf[i*4+3] = 255;
- }
+ this._damageQueued = false;
+ this._resizeFromCanvas();
+ }
+ _canvasDimension(name, fallback) {
+ const raw = this.canvas.getAttribute(name);
+ if (raw === null || raw === '') return fallback;
+ const parsed = Number.parseInt(raw, 10);
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
+ }
+ _resetDrawingState() {
this.fillStyle = '#000000';
this.strokeStyle = '#000000';
this.lineWidth = 1;
@@ -10230,6 +10234,39 @@ class _Canvas2D {
this.globalCompositeOperation = 'source-over';
this._stateStack = [];
}
+ _resizeFromCanvas() {
+ const requestedWidth = this._canvasDimension('width', 300);
+ const requestedHeight = this._canvasDimension('height', 150);
+ const valid = requestedWidth <= _MAX_CANVAS_DIMENSION
+ && requestedHeight <= _MAX_CANVAS_DIMENSION
+ && requestedWidth * requestedHeight <= _MAX_CANVAS_PIXELS;
+ this._w = valid ? requestedWidth : 0;
+ this._h = valid ? requestedHeight : 0;
+ this._buf = new Uint8ClampedArray(this._w * this._h * 4);
+ this._resetDrawingState();
+ const register = Deno.core.ops.op_canvas_register_surface;
+ if (typeof register === 'function') {
+ // op2 accepts Uint8Array, while Canvas exposes Uint8ClampedArray. This
+ // second view shares the exact backing store; no pixel copy is made.
+ const bytes = new Uint8Array(
+ this._buf.buffer,
+ this._buf.byteOffset,
+ this._buf.byteLength,
+ );
+ if (!register(this.canvas._nid, this._w, this._h, bytes)) {
+ throw new RangeError('Canvas backing store allocation failed');
+ }
+ }
+ }
+ _markPaintDamage() {
+ if (this._damageQueued) return;
+ this._damageQueued = true;
+ queueMicrotask(() => {
+ this._damageQueued = false;
+ const damage = Deno.core.ops.op_canvas_paint_damage;
+ if (typeof damage === 'function') damage(this.canvas._nid);
+ });
+ }
_parseColor(css) {
if (!css || typeof css !== 'string' || css === 'none') return [0,0,0,0];
if (css.startsWith('#')) {
@@ -10268,6 +10305,7 @@ class _Canvas2D {
this._setPixel(px, py, r, g, b, a);
}
}
+ this._markPaintDamage();
}
clearRect(x, y, w, h) {
x=Math.round(x); y=Math.round(y); w=Math.round(w); h=Math.round(h);
@@ -10277,6 +10315,7 @@ class _Canvas2D {
this._buf[idx] = this._buf[idx+1] = this._buf[idx+2] = this._buf[idx+3] = 0;
}
}
+ this._markPaintDamage();
}
strokeRect(x, y, w, h) {
const [r,g,b,a] = this._parseColor(this.strokeStyle);
@@ -10287,6 +10326,7 @@ class _Canvas2D {
for (let py = Math.round(y); py < Math.round(y+h); py++) {
for (let l = 0; l < lw; l++) { this._setPixel(Math.round(x)+l, py, r,g,b,a); this._setPixel(Math.round(x+w)-1-l, py, r,g,b,a); }
}
+ this._markPaintDamage();
}
fillText(text, x, y) {
const [r,g,b,a] = this._parseColor(this.fillStyle);
@@ -10312,6 +10352,7 @@ class _Canvas2D {
}
cx += 6 * scale;
}
+ this._markPaintDamage();
}
strokeText(text, x, y) { this.fillText(text, x, y); }
measureText(t) {
@@ -10353,6 +10394,7 @@ class _Canvas2D {
}
}
}
+ this._markPaintDamage();
}
createImageData(w, h) { return { data: new Uint8ClampedArray(w*h*4), width: w, height: h }; }
drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh) {
@@ -10370,6 +10412,7 @@ class _Canvas2D {
}
}
}
+ this._markPaintDamage();
}
beginPath() { this._path = []; }
closePath() {}
@@ -10394,6 +10437,7 @@ class _Canvas2D {
}
}
this._path = [];
+ this._markPaintDamage();
}
stroke() {}
clip() {}
@@ -10417,10 +10461,41 @@ class _Canvas2D {
getContextAttributes() { return { alpha: true, desynchronized: false, colorSpace: "srgb", willReadFrequently: false }; }
}
-Element.prototype.getContext = function getContext(type) {
+class HTMLCanvasElement extends Element {
+ get width() {
+ const raw = this.getAttribute('width');
+ const parsed = raw === null ? 300 : Number.parseInt(raw, 10);
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 300;
+ }
+ set width(value) { this.setAttribute('width', Math.max(0, Number(value) || 0)); }
+ get height() {
+ const raw = this.getAttribute('height');
+ const parsed = raw === null ? 150 : Number.parseInt(raw, 10);
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 150;
+ }
+ set height(value) { this.setAttribute('height', Math.max(0, Number(value) || 0)); }
+ setAttribute(name, value) {
+ super.setAttribute(name, value);
+ const normalized = String(name).toLowerCase();
+ if (this._ctx && (normalized === 'width' || normalized === 'height')) {
+ this._ctx._resizeFromCanvas();
+ }
+ }
+ removeAttribute(name) {
+ super.removeAttribute(name);
+ const normalized = String(name).toLowerCase();
+ if (this._ctx && (normalized === 'width' || normalized === 'height')) {
+ this._ctx._resizeFromCanvas();
+ }
+ }
+}
+globalThis.HTMLCanvasElement = HTMLCanvasElement;
+
+HTMLCanvasElement.prototype.getContext = function getContext(type) {
if (type === '2d') {
if (!this._ctx) {
- this._ctx = new _Canvas2D(this);
+ try { this._ctx = new _Canvas2D(this); }
+ catch (_error) { return null; }
}
return this._ctx;
}
@@ -10434,22 +10509,31 @@ Element.prototype.getContext = function getContext(type) {
}
return null;
};
-Element.prototype.toDataURL = function(type) {
- if (this._ctx && this._ctx._buf) {
- const ctx = this._ctx;
+HTMLCanvasElement.prototype.toDataURL = function(type) {
+ const ctx = this._ctx || this.getContext('2d');
+ if (ctx && ctx._buf) {
+ if (ctx._w === 0 || ctx._h === 0) return 'data:,';
return _encodePNG(ctx._w, ctx._h, ctx._buf);
}
- return _fp('canvasFingerprint');
+ return 'data:,';
+};
+HTMLCanvasElement.prototype.toBlob = function(cb, type, q) {
+ const url = this.toDataURL(type, q);
+ const comma = url.indexOf(',');
+ if (comma < 0 || !url.startsWith('data:image/')) { cb(null); return; }
+ const binary = atob(url.slice(comma + 1));
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
+ cb(new Blob([bytes], {type: String(type || 'image/png')}));
};
-Element.prototype.toBlob = function(cb, type, q) { cb(new Blob([''])); };
Element.prototype.getBBox = function() { return { x: 0, y: 0, width: 0, height: 0 }; };
Element.prototype.getComputedTextLength = function() { return 0; };
Element.prototype.getExtentOfChar = function(ch) { return { x: 0, y: 0, width: 0, height: 0 }; };
Element.prototype.getSubStringLength = function(ch, len) { return 0; };
-_markNative(Element.prototype.getContext);
-_markNative(Element.prototype.toDataURL);
-_markNative(Element.prototype.toBlob);
+_markNative(HTMLCanvasElement.prototype.getContext);
+_markNative(HTMLCanvasElement.prototype.toDataURL);
+_markNative(HTMLCanvasElement.prototype.toBlob);
Element.prototype.attachShadow = function attachShadow(opts) {
var _mode = opts == null ? undefined : opts.mode;
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index ed8ffd58..a730ae56 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -6,6 +6,8 @@ use std::sync::Arc;
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use deno_core::op2;
use deno_core::Extension;
+#[cfg(feature = "render")]
+use deno_core::JsBuffer;
use deno_core::OpState;
use obscura_dom::{DomTree, NodeData, NodeId};
#[cfg(feature = "render")]
@@ -82,6 +84,17 @@ pub struct JsNetworkEvent {
#[cfg(feature = "render")]
pub use obscura_render::ImageRequestProfile;
+/// A live Canvas2D backing store retained from V8. `JsBuffer` owns a shared
+/// reference to the ArrayBuffer backing store, so the pixels stay valid while
+/// the canvas wrapper and native page state share it. Paint only borrows these
+/// bytes synchronously while JavaScript is not executing.
+#[cfg(feature = "render")]
+pub(crate) struct CanvasBackingSurface {
+ pub width: u32,
+ pub height: u32,
+ pub pixels: JsBuffer,
+}
+
pub struct ObscuraState {
pub dom: Option<DomTree>,
pub url: String,
@@ -185,6 +198,10 @@ pub struct ObscuraState {
/// `<style>` element merely to feed the renderer.
#[cfg(feature = "render")]
pub dynamic_fonts: Vec<obscura_render::DynamicFontFace>,
+ /// Live Canvas2D backing stores keyed by stable DOM identity. Pixel damage
+ /// updates this resource independently of retained style/layout geometry.
+ #[cfg(feature = "render")]
+ pub(crate) canvas_surfaces: HashMap<NodeId, CanvasBackingSurface>,
#[cfg(feature = "render")]
pub viewport: (f32, f32),
/// Root scrolling offset in CSS pixels. With render enabled this is
@@ -262,6 +279,8 @@ impl ObscuraState {
#[cfg(feature = "render")]
dynamic_fonts: Vec::new(),
#[cfg(feature = "render")]
+ canvas_surfaces: HashMap::new(),
+ #[cfg(feature = "render")]
viewport: (1280.0, 720.0),
#[cfg(feature = "render")]
scroll_offset: (0.0, 0.0),
@@ -3217,6 +3236,92 @@ fn op_set_dynamic_fonts(state: &OpState, #[string] registrations: &str) -> bool
true
}
+/// Retain the JavaScript-owned Canvas2D pixel buffer without copying it. A
+/// canvas resize supplies a new fixed backing store and atomically replaces
+/// the previous surface for the same DOM node.
+#[cfg(feature = "render")]
+#[op2]
+fn op_canvas_register_surface(
+ state: &OpState,
+ nid: u32,
+ width: u32,
+ height: u32,
+ #[buffer] pixels: JsBuffer,
+) -> bool {
+ const MAX_CANVAS_DIMENSION: u32 = 32_767;
+ const MAX_CANVAS_PIXELS: usize = 67_108_864;
+ const MAX_CANVAS_SURFACE_BYTES: usize = 256 * 1024 * 1024;
+ let Some(expected) = (width as usize)
+ .checked_mul(height as usize)
+ .and_then(|pixels| pixels.checked_mul(4))
+ else {
+ return false;
+ };
+ if width > MAX_CANVAS_DIMENSION
+ || height > MAX_CANVAS_DIMENSION
+ || expected / 4 > MAX_CANVAS_PIXELS
+ || pixels.len() != expected
+ {
+ return false;
+ }
+
+ let shared = state.borrow::<SharedState>().clone();
+ let mut state = shared.borrow_mut();
+ let node = NodeId::new(nid);
+ let is_canvas = state
+ .dom
+ .as_ref()
+ .and_then(|dom| dom.get_node(node))
+ .is_some_and(|node| {
+ node.as_element()
+ .is_some_and(|name| name.local.as_ref() == "canvas")
+ });
+ if !is_canvas {
+ return false;
+ }
+ let replacing = state.canvas_surfaces.get(&node).map(|surface| surface.pixels.len());
+ let retained_bytes = state
+ .canvas_surfaces
+ .values()
+ .try_fold(0usize, |total, surface| total.checked_add(surface.pixels.len()))
+ .and_then(|total| total.checked_sub(replacing.unwrap_or(0)))
+ .and_then(|total| total.checked_add(expected));
+ if retained_bytes.is_none_or(|bytes| bytes > MAX_CANVAS_SURFACE_BYTES) {
+ return false;
+ }
+ state.canvas_surfaces.insert(
+ node,
+ CanvasBackingSurface {
+ width,
+ height,
+ pixels,
+ },
+ );
+ true
+}
+
+/// Report one coalesced Canvas2D paint at the JavaScript task boundary. Pixel
+/// bytes are already live through the retained backing store, so damage wakes
+/// screencast/readiness without throwing away otherwise-valid layout.
+#[cfg(feature = "render")]
+#[op2(fast)]
+fn op_canvas_paint_damage(state: &OpState, nid: u32) -> bool {
+ let shared = state.borrow::<SharedState>().clone();
+ let mut state = shared.borrow_mut();
+ let node = NodeId::new(nid);
+ if !state.canvas_surfaces.contains_key(&node) {
+ return false;
+ }
+ let connected = state
+ .dom
+ .as_ref()
+ .is_some_and(|dom| node_is_connected(dom, node));
+ if connected {
+ state.activity_generation = state.activity_generation.wrapping_add(1);
+ }
+ connected
+}
+
pub fn build_extension() -> Extension {
let mut ops = vec![
op_dom(),
@@ -3252,6 +3357,8 @@ pub fn build_extension() -> Extension {
{
ops.push(op_begin_render_task());
ops.push(op_set_dynamic_fonts());
+ ops.push(op_canvas_register_surface());
+ ops.push(op_canvas_paint_damage());
ops.push(op_image_metadata());
ops.push(op_load_image_metadata());
ops.push(op_layout_geometry());
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index ee7ffc00..e18036d3 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -19,6 +19,23 @@ use crate::ops::{
begin_animation_task, clamp_scroll_offset, document_base_url, ensure_resolved_scroll,
};
+#[cfg(feature = "render")]
+struct RuntimeCanvasSurfaceSource<'a>(
+ &'a HashMap<NodeId, crate::ops::CanvasBackingSurface>,
+);
+
+#[cfg(feature = "render")]
+impl obscura_render::CanvasSurfaceSource for RuntimeCanvasSurfaceSource<'_> {
+ fn surface(&self, node: NodeId) -> Option<obscura_render::CanvasSurface<'_>> {
+ let surface = self.0.get(&node)?;
+ obscura_render::CanvasSurface::from_rgba8(
+ surface.width,
+ surface.height,
+ surface.pixels.as_ref(),
+ )
+ }
+}
+
static SNAPSHOT: &[u8] = include_bytes!(env!("OBSCURA_SNAPSHOT_PATH"));
/// Serializes V8 isolate construction across OS threads. The thread-per-
@@ -292,6 +309,7 @@ impl ObscuraJsRuntime {
gs.render_image_in_flight.clear();
gs.stylesheet_cache = obscura_render::StylesheetCache::default();
gs.dynamic_fonts.clear();
+ gs.canvas_surfaces.clear();
gs.scroll_offset = (0.0, 0.0);
gs.element_scroll_offsets.clear();
gs.scroll_generation = 0;
@@ -583,15 +601,18 @@ impl ObscuraJsRuntime {
prepared_render,
render_resources,
resolved_scroll,
+ canvas_surfaces,
..
} = state;
let (_, scroll) = resolved_scroll.as_ref()?;
- obscura_render::screenshot_prepared_with_scroll_and_surface_color(
+ let canvas_surfaces = RuntimeCanvasSurfaceSource(canvas_surfaces);
+ obscura_render::screenshot_prepared_with_scroll_and_surface_color_and_canvas_surfaces(
dom.as_ref()?,
prepared_render.as_mut()?,
render_resources,
scroll,
surface_color,
+ &canvas_surfaces,
)
})
}
@@ -621,12 +642,14 @@ impl ObscuraJsRuntime {
prepared_render,
render_resources,
resolved_scroll,
+ canvas_surfaces,
..
} = state;
let (_, scroll) = resolved_scroll
.as_ref()
.ok_or(obscura_render::CaptureError::PaintFailed)?;
- obscura_render::screenshot_prepared_region_with_scroll_and_surface_color(
+ let canvas_surfaces = RuntimeCanvasSurfaceSource(canvas_surfaces);
+ obscura_render::screenshot_prepared_region_with_scroll_and_surface_color_and_canvas_surfaces(
dom.as_ref()
.ok_or(obscura_render::CaptureError::PaintFailed)?,
prepared_render
@@ -636,6 +659,7 @@ impl ObscuraJsRuntime {
scroll,
region,
surface_color,
+ &canvas_surfaces,
)
})
}
@@ -656,12 +680,14 @@ impl ObscuraJsRuntime {
prepared_render,
render_resources,
resolved_scroll,
+ canvas_surfaces,
..
} = state;
let (_, scroll) = resolved_scroll
.as_ref()
.ok_or(obscura_render::CaptureError::PaintFailed)?;
- obscura_render::screenshot_prepared_region_with_scroll_and_backgrounds(
+ let canvas_surfaces = RuntimeCanvasSurfaceSource(canvas_surfaces);
+ obscura_render::screenshot_prepared_region_with_scroll_and_backgrounds_and_canvas_surfaces(
dom.as_ref()
.ok_or(obscura_render::CaptureError::PaintFailed)?,
prepared_render
@@ -671,6 +697,7 @@ impl ObscuraJsRuntime {
scroll,
region,
paint_backgrounds,
+ &canvas_surfaces,
)
})
}
@@ -694,6 +721,7 @@ impl ObscuraJsRuntime {
prepared_render,
render_resources,
element_scroll_offsets,
+ canvas_surfaces,
..
} = state;
let dom = dom
@@ -708,7 +736,8 @@ impl ObscuraJsRuntime {
element_scroll_offsets,
(region.width, region.height),
);
- obscura_render::screenshot_prepared_region_with_scroll_and_backgrounds(
+ let canvas_surfaces = RuntimeCanvasSurfaceSource(canvas_surfaces);
+ obscura_render::screenshot_prepared_region_with_scroll_and_backgrounds_and_canvas_surfaces(
dom,
prepared_render
.as_mut()
@@ -717,6 +746,7 @@ impl ObscuraJsRuntime {
&scroll,
region,
paint_backgrounds,
+ &canvas_surfaces,
)
})
}
@@ -8899,6 +8929,166 @@ mod tests {
);
}
+ #[cfg(feature = "render")]
+ #[test]
+ fn canvas_2d_live_backing_paints_immediately_with_scaling_clips_and_effects() {
+ let dom = parse_html(
+ r#"<html style="margin:0"><body style="margin:0;width:64px;height:40px;background:#0000ff">
+ <div style="position:absolute;left:4px;top:4px;width:18px;height:14px;overflow:hidden">
+ <canvas id="paint" width="2" height="1"
+ style="display:block;width:20px;height:10px;border:2px solid #ffff00;opacity:.5"></canvas>
+ </div>
+ <canvas id="blank" width="4" height="4"
+ style="position:absolute;left:30px;top:4px;width:10px;height:10px"></canvas>
+ <canvas id="padding" width="2" height="1"
+ style="position:absolute;left:30px;top:20px;width:10px;height:4px;padding:2px 2px 2px 4px;border:1px solid #ffff00;background:#00ffff"></canvas>
+ <div style="position:absolute;z-index:2;left:10px;top:7px;width:4px;height:4px;background:#ff00ff"></div>
+ </body></html>"#,
+ );
+ let mut rt = ObscuraJsRuntime::new();
+ rt.set_dom(dom);
+ rt.set_url("http://example.test/canvas");
+ rt.set_viewport(64.0, 40.0);
+ rt.run_page_init();
+
+ let blank_api = rt
+ .evaluate(
+ r#"(() => {
+ const blank = document.getElementById('blank');
+ const encoded = blank.toDataURL();
+ const blankContext = blank.getContext('2d');
+ const pixels = blankContext.getImageData(0, 0, 4, 4).data;
+ blankContext.fillStyle = '#ff0000'; blankContext.fillRect(0, 0, 1, 1);
+ blank.width = 6;
+ const resetPixel = blankContext.getImageData(0, 0, 1, 1).data;
+ const untouched = document.createElement('canvas');
+ const defaultEncoded = untouched.toDataURL();
+ const defaultPixels = untouched.getContext('2d').getImageData(0, 0, 1, 1).data;
+ return [
+ blank instanceof HTMLCanvasElement,
+ typeof document.createElement('div').getContext,
+ blank.width, blank.height, blank.getContext('2d') === blankContext,
+ encoded.startsWith('data:image/png;base64,'),
+ atob(encoded.split(',')[1]).charCodeAt(25) === 6,
+ Array.from(pixels).every((value, index) => index % 4 !== 3 || value === 0),
+ untouched.width, untouched.height,
+ defaultEncoded.startsWith('data:image/png;base64,'),
+ Array.from(defaultPixels),
+ Array.from(resetPixel),
+ ];
+ })()"#,
+ )
+ .expect("transparent default canvas API");
+ assert_eq!(
+ blank_api,
+ serde_json::json!([
+ true,
+ "undefined",
+ 6,
+ 4,
+ true,
+ true,
+ true,
+ true,
+ 300,
+ 150,
+ true,
+ [0, 0, 0, 0],
+ [0, 0, 0, 0]
+ ])
+ );
+
+ // Prepare layout before drawing so the assertions below prove canvas
+ // damage retains layout, while the following capture proves pixels
+ // are read from the live backing immediately after the script task.
+ {
+ let mut state = rt.state.borrow_mut();
+ ensure_resolved_scroll(&mut state).expect("initial resolved canvas scroll");
+ }
+ let prepared_address = {
+ let state = rt.state.borrow();
+ state.prepared_render.as_ref().unwrap() as *const _ as usize
+ };
+ let activity_before = rt.activity_generation();
+ rt.execute_script(
+ "canvas-fill",
+ r#"const canvas = document.getElementById('paint');
+ const ctx = canvas.getContext('2d');
+ ctx.fillStyle = '#ff0000'; ctx.fillRect(0, 0, 1, 1);
+ ctx.fillStyle = '#00ff00'; ctx.fillRect(1, 0, 1, 1);
+ const padding = document.getElementById('padding').getContext('2d');
+ padding.fillStyle = '#ff0000'; padding.fillRect(0, 0, 1, 1);
+ padding.fillStyle = '#00ff00'; padding.fillRect(1, 0, 1, 1);"#,
+ )
+ .expect("fill live canvas backing");
+ assert!(rt.activity_generation() > activity_before);
+ assert_eq!(
+ rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize,
+ prepared_address,
+ "canvas damage must not invalidate retained layout"
+ );
+
+ let pixmap = {
+ let mut state = rt.state.borrow_mut();
+ ensure_resolved_scroll(&mut state).expect("resolved canvas scroll");
+ let ObscuraState {
+ dom,
+ prepared_render,
+ render_resources,
+ resolved_scroll,
+ canvas_surfaces,
+ ..
+ } = &mut *state;
+ let (_, scroll) = resolved_scroll.as_ref().expect("scroll snapshot");
+ let canvas_surfaces = RuntimeCanvasSurfaceSource(canvas_surfaces);
+ obscura_render::paint_prepared_with_scroll_and_surface_color_and_canvas_surfaces(
+ dom.as_ref().expect("canvas DOM"),
+ prepared_render.as_mut().expect("prepared canvas layout"),
+ render_resources,
+ scroll,
+ [255, 255, 255, 255],
+ &canvas_surfaces,
+ )
+ .expect("canvas pixmap")
+ };
+
+ let red_half = pixmap.pixel(7, 8).expect("scaled red canvas pixel");
+ assert!(red_half.red() > 100 && red_half.blue() > 100 && red_half.green() < 20);
+ // Bilinear filtering blends at the exact source-pixel transition
+ // (x=16), so sample several CSS pixels into the green half.
+ let green_half = pixmap.pixel(19, 8).expect("scaled green canvas pixel");
+ assert!(
+ green_half.green() > 45 && green_half.blue() > 100 && green_half.red() < 20,
+ "pixel at (19, 8) was rgba({}, {}, {}, {})",
+ green_half.red(),
+ green_half.green(),
+ green_half.blue(),
+ green_half.alpha()
+ );
+ let clipped = pixmap.pixel(23, 8).expect("outside overflow clip");
+ assert_eq!((clipped.red(), clipped.green(), clipped.blue()), (0, 0, 255));
+ let blank = pixmap.pixel(34, 8).expect("transparent blank canvas");
+ assert_eq!((blank.red(), blank.green(), blank.blue()), (0, 0, 255));
+ let overlay = pixmap.pixel(11, 8).expect("higher z-index overlay");
+ assert!(overlay.red() > 240 && overlay.blue() > 240 && overlay.green() < 20);
+ let border = pixmap.pixel(4, 8).expect("canvas border above content");
+ assert!(border.red() > 100 && border.green() > 100 && border.blue() > 100);
+ let padding = pixmap.pixel(33, 23).expect("canvas padding pixel");
+ assert_eq!(
+ (padding.red(), padding.green(), padding.blue()),
+ (0, 255, 255),
+ "canvas pixels must not cover authored padding"
+ );
+ let padded_content = pixmap.pixel(36, 23).expect("padded canvas content pixel");
+ assert!(
+ padded_content.red() > 220
+ && padded_content.green() < 40
+ && padded_content.blue() < 40,
+ "canvas bitmap must start at the CSS content-box origin"
+ );
+
+ }
+
#[test]
fn test_script_execution() {
let mut rt = setup_runtime("<ul><li>A</li><li>B</li></ul>");
diff --git a/crates/obscura-render/src/lib.rs b/crates/obscura-render/src/lib.rs
index 8b39445b..1fd63817 100644
--- a/crates/obscura-render/src/lib.rs
+++ b/crates/obscura-render/src/lib.rs
@@ -101,7 +101,9 @@ pub use paint::{
paint_dom_scrolled_at_animation_time,
paint_dom_scrolled_at_animation_time_with_surface_color, paint_prepared,
paint_prepared_region_with_scroll, paint_prepared_region_with_scroll_and_surface_color,
- paint_prepared_with_scroll, paint_prepared_with_scroll_and_surface_color, prepare_dom,
+ paint_prepared_region_with_scroll_and_surface_color_and_canvas_surfaces,
+ paint_prepared_with_scroll, paint_prepared_with_scroll_and_surface_color,
+ paint_prepared_with_scroll_and_surface_color_and_canvas_surfaces, prepare_dom,
prepare_dom_at_animation_time,
prepare_dom_with_dynamic_fonts, prepare_dom_with_dynamic_fonts_at_animation_time,
prepare_dom_with_dynamic_fonts_and_stylesheet_cache,
@@ -116,10 +118,14 @@ pub use paint::{
screenshot_prepared,
screenshot_prepared_region_with_scroll,
screenshot_prepared_region_with_scroll_and_surface_color,
- screenshot_prepared_region_with_scroll_and_backgrounds, screenshot_prepared_with_scroll,
+ screenshot_prepared_region_with_scroll_and_surface_color_and_canvas_surfaces,
+ screenshot_prepared_region_with_scroll_and_backgrounds,
+ screenshot_prepared_region_with_scroll_and_backgrounds_and_canvas_surfaces,
+ screenshot_prepared_with_scroll,
screenshot_prepared_with_scroll_and_surface_color,
+ screenshot_prepared_with_scroll_and_surface_color_and_canvas_surfaces,
validate_capture_region, CaptureError, CaptureRegion, DynamicFontFace, ElementScrollMetrics,
- ImageRequestProfile, PreparedRender, RenderResourceCache, RenderResourceLoader,
+ CanvasSurface, CanvasSurfaceSource, ImageRequestProfile, PreparedRender, RenderResourceCache, RenderResourceLoader,
ResolvedScrollState, SelectedImage,
MAX_CAPTURE_DIMENSION, MAX_CAPTURE_PIXELS,
};
diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rs
index 8bd6b415..48672874 100644
--- a/crates/obscura-render/src/paint.rs
+++ b/crates/obscura-render/src/paint.rs
@@ -607,6 +607,45 @@ pub struct SelectedImage {
pub profile: ImageRequestProfile,
}
+/// A short-lived view of one JavaScript canvas backing store. The renderer
+/// deliberately borrows raw RGBA only for a synchronous paint; retained
+/// layout never owns VM-specific resources or pixel copies.
+#[derive(Clone, Copy, Debug)]
+pub struct CanvasSurface<'a> {
+ width: u32,
+ height: u32,
+ rgba: &'a [u8],
+}
+
+impl<'a> CanvasSurface<'a> {
+ pub fn from_rgba8(width: u32, height: u32, rgba: &'a [u8]) -> Option<Self> {
+ let expected = (width as usize)
+ .checked_mul(height as usize)?
+ .checked_mul(4)?;
+ (expected == rgba.len()).then_some(Self {
+ width,
+ height,
+ rgba,
+ })
+ }
+}
+
+/// Paint-time lookup for dynamic canvas pixels. Implementations may retain a
+/// VM backing store, but the returned slice cannot escape the capture call.
+pub trait CanvasSurfaceSource {
+ fn surface(&self, node: obscura_dom::tree::NodeId) -> Option<CanvasSurface<'_>>;
+}
+
+struct EmptyCanvasSurfaceSource;
+
+impl CanvasSurfaceSource for EmptyCanvasSurfaceSource {
+ fn surface(&self, _node: obscura_dom::tree::NodeId) -> Option<CanvasSurface<'_>> {
+ None
+ }
+}
+
+static EMPTY_CANVAS_SURFACES: EmptyCanvasSurfaceSource = EmptyCanvasSurfaceSource;
+
/// CSSOM scrolling metrics for one element box. Non-scroll containers expose
/// their padding-box size on both surfaces and retain a zero offset.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -2393,6 +2432,7 @@ fn paint_prepared_with_surface_color(
pixmap,
resources,
&prepared.selected_images,
+ &EMPTY_CANVAS_SURFACES,
&prepared.svg_fonts,
prepared.content_size,
&prepared.viewport_fixed,
@@ -2434,6 +2474,24 @@ pub fn paint_prepared_with_scroll_and_surface_color(
resources: &mut RenderResourceCache,
scroll: &ResolvedScrollState,
surface_color: [u8; 4],
+) -> Option<Pixmap> {
+ paint_prepared_with_scroll_and_surface_color_and_canvas_surfaces(
+ tree,
+ prepared,
+ resources,
+ scroll,
+ surface_color,
+ &EMPTY_CANVAS_SURFACES,
+ )
+}
+
+pub fn paint_prepared_with_scroll_and_surface_color_and_canvas_surfaces(
+ tree: &DomTree,
+ prepared: &mut PreparedRender,
+ resources: &mut RenderResourceCache,
+ scroll: &ResolvedScrollState,
+ surface_color: [u8; 4],
+ canvas_surfaces: &dyn CanvasSurfaceSource,
) -> Option<Pixmap> {
validate_capture_region(CaptureRegion::new(
scroll.root_offset().0,
@@ -2461,6 +2519,7 @@ pub fn paint_prepared_with_scroll_and_surface_color(
pixmap,
resources,
&prepared.selected_images,
+ canvas_surfaces,
&prepared.svg_fonts,
prepared.content_size,
&prepared.viewport_fixed,
@@ -2507,6 +2566,26 @@ pub fn paint_prepared_region_with_scroll_and_surface_color(
scroll: &ResolvedScrollState,
region: CaptureRegion,
surface_color: [u8; 4],
+) -> Result<Pixmap, CaptureError> {
+ paint_prepared_region_with_scroll_and_surface_color_and_canvas_surfaces(
+ tree,
+ prepared,
+ resources,
+ scroll,
+ region,
+ surface_color,
+ &EMPTY_CANVAS_SURFACES,
+ )
+}
+
+pub fn paint_prepared_region_with_scroll_and_surface_color_and_canvas_surfaces(
+ tree: &DomTree,
+ prepared: &mut PreparedRender,
+ resources: &mut RenderResourceCache,
+ scroll: &ResolvedScrollState,
+ region: CaptureRegion,
+ surface_color: [u8; 4],
+ canvas_surfaces: &dyn CanvasSurfaceSource,
) -> Result<Pixmap, CaptureError> {
paint_prepared_region_with_scroll_policy(
tree,
@@ -2516,6 +2595,7 @@ pub fn paint_prepared_region_with_scroll_and_surface_color(
region,
false,
surface_color,
+ canvas_surfaces,
)
}
@@ -2525,6 +2605,7 @@ fn paint_prepared_region_with_scroll_with_print_economy(
resources: &mut RenderResourceCache,
scroll: &ResolvedScrollState,
region: CaptureRegion,
+ canvas_surfaces: &dyn CanvasSurfaceSource,
) -> Result<Pixmap, CaptureError> {
paint_prepared_region_with_scroll_policy(
tree,
@@ -2534,6 +2615,7 @@ fn paint_prepared_region_with_scroll_with_print_economy(
region,
true,
[255, 255, 255, 255],
+ canvas_surfaces,
)
}
@@ -2545,6 +2627,7 @@ fn paint_prepared_region_with_scroll_policy(
region: CaptureRegion,
print_economy: bool,
surface_color: [u8; 4],
+ canvas_surfaces: &dyn CanvasSurfaceSource,
) -> Result<Pixmap, CaptureError> {
let (native_width, native_height, output_width, output_height) =
checked_capture_dimensions(region)?;
@@ -2586,6 +2669,7 @@ fn paint_prepared_region_with_scroll_policy(
pixmap,
resources,
&prepared.selected_images,
+ canvas_surfaces,
&prepared.svg_fonts,
prepared.content_size,
&prepared.viewport_fixed,
@@ -2998,6 +3082,7 @@ fn paint_laid_dom_scrolled(
mut pixmap: Pixmap,
image_cache: &mut RenderResourceCache,
selected_images: &HashMap<obscura_dom::tree::NodeId, SelectedImage>,
+ canvas_surfaces: &dyn CanvasSurfaceSource,
svg_fonts: &Arc<usvg::fontdb::Database>,
content_size: (f32, f32),
viewport_fixed: &std::collections::HashSet<obscura_dom::tree::NodeId>,
@@ -3260,6 +3345,7 @@ fn paint_laid_dom_scrolled(
pixmap,
image_cache,
selected_images,
+ canvas_surfaces,
svg_fonts,
content_size,
viewport_fixed,
@@ -3294,6 +3380,7 @@ fn paint_laid_dom_scrolled(
pixmap,
image_cache,
selected_images,
+ canvas_surfaces,
svg_fonts,
content_size,
viewport_fixed,
@@ -3395,6 +3482,7 @@ fn paint_laid_dom_scrolled(
pixmap,
image_cache,
selected_images,
+ canvas_surfaces,
svg_fonts,
content_size,
viewport_fixed,
@@ -3468,6 +3556,7 @@ fn paint_laid_dom_scrolled(
layer,
image_cache,
selected_images,
+ canvas_surfaces,
svg_fonts,
content_size,
viewport_fixed,
@@ -3542,6 +3631,7 @@ fn paint_laid_dom_scrolled(
layer,
image_cache,
selected_images,
+ canvas_surfaces,
svg_fonts,
content_size,
viewport_fixed,
@@ -3942,6 +4032,38 @@ fn paint_laid_dom_scrolled(
}
}
+ if box_on_surface && name.local.as_ref() == "canvas" {
+ if let Some(surface) = canvas_surfaces.surface(nid) {
+ // A canvas bitmap is replaced content: CSS sizing and
+ // object-fit operate on the content box, never the padding or
+ // border box. Keep padding available for the element's own
+ // background and inset the rounded clip to the same edge.
+ let content_insets = crate::Sides {
+ top: style.border.top + style.padding.top,
+ right: style.border.right + style.padding.right,
+ bottom: style.border.bottom + style.padding.bottom,
+ left: style.border.left + style.padding.left,
+ };
+ let content_rect = crate::Rect {
+ x: rect.x + content_insets.left,
+ y: rect.y + content_insets.top,
+ width: (rect.width - content_insets.left - content_insets.right).max(0.0),
+ height: (rect.height - content_insets.top - content_insets.bottom).max(0.0),
+ };
+ let content_visible = content_rect.intersect(&visible_rect).unwrap_or_default();
+ paint_canvas_surface(
+ surface,
+ &content_rect,
+ &content_visible,
+ style.object_fit,
+ style.object_position,
+ &mut pixmap,
+ radius.inset(content_insets),
+ element_clip_mask,
+ );
+ }
+ }
+
if !paints_inline_fragments {
paint_css_border(
&mut pixmap,
@@ -5734,6 +5856,26 @@ pub fn screenshot_prepared_with_scroll_and_surface_color(
.ok()
}
+pub fn screenshot_prepared_with_scroll_and_surface_color_and_canvas_surfaces(
+ tree: &DomTree,
+ prepared: &mut PreparedRender,
+ resources: &mut RenderResourceCache,
+ scroll: &ResolvedScrollState,
+ surface_color: [u8; 4],
+ canvas_surfaces: &dyn CanvasSurfaceSource,
+) -> Option<Vec<u8>> {
+ paint_prepared_with_scroll_and_surface_color_and_canvas_surfaces(
+ tree,
+ prepared,
+ resources,
+ scroll,
+ surface_color,
+ canvas_surfaces,
+ )?
+ .encode_png()
+ .ok()
+}
+
/// PNG convenience wrapper for [`paint_prepared_region_with_scroll`].
pub fn screenshot_prepared_region_with_scroll(
tree: &DomTree,
@@ -5767,6 +5909,28 @@ pub fn screenshot_prepared_region_with_scroll_and_surface_color(
.map_err(|_| CaptureError::EncodeFailed)
}
+pub fn screenshot_prepared_region_with_scroll_and_surface_color_and_canvas_surfaces(
+ tree: &DomTree,
+ prepared: &mut PreparedRender,
+ resources: &mut RenderResourceCache,
+ scroll: &ResolvedScrollState,
+ region: CaptureRegion,
+ surface_color: [u8; 4],
+ canvas_surfaces: &dyn CanvasSurfaceSource,
+) -> Result<Vec<u8>, CaptureError> {
+ paint_prepared_region_with_scroll_and_surface_color_and_canvas_surfaces(
+ tree,
+ prepared,
+ resources,
+ scroll,
+ region,
+ surface_color,
+ canvas_surfaces,
+ )?
+ .encode_png()
+ .map_err(|_| CaptureError::EncodeFailed)
+}
+
/// Capture a retained region using the PDF print-background policy. Ordinary
/// screenshots pass `true`. When false, authored fills are replaced with the
/// browser print-economy white fill and light text is darkened for legibility;
@@ -5778,9 +5942,39 @@ pub fn screenshot_prepared_region_with_scroll_and_backgrounds(
scroll: &ResolvedScrollState,
region: CaptureRegion,
paint_backgrounds: bool,
+) -> Result<Vec<u8>, CaptureError> {
+ screenshot_prepared_region_with_scroll_and_backgrounds_and_canvas_surfaces(
+ tree,
+ prepared,
+ resources,
+ scroll,
+ region,
+ paint_backgrounds,
+ &EMPTY_CANVAS_SURFACES,
+ )
+}
+
+pub fn screenshot_prepared_region_with_scroll_and_backgrounds_and_canvas_surfaces(
+ tree: &DomTree,
+ prepared: &mut PreparedRender,
+ resources: &mut RenderResourceCache,
+ scroll: &ResolvedScrollState,
+ region: CaptureRegion,
+ paint_backgrounds: bool,
+ canvas_surfaces: &dyn CanvasSurfaceSource,
) -> Result<Vec<u8>, CaptureError> {
if paint_backgrounds {
- return screenshot_prepared_region_with_scroll(tree, prepared, resources, scroll, region);
+ return paint_prepared_region_with_scroll_and_surface_color_and_canvas_surfaces(
+ tree,
+ prepared,
+ resources,
+ scroll,
+ region,
+ [255, 255, 255, 255],
+ canvas_surfaces,
+ )?
+ .encode_png()
+ .map_err(|_| CaptureError::EncodeFailed);
}
let snapshots = prepared
@@ -5790,7 +5984,12 @@ pub fn screenshot_prepared_region_with_scroll_and_backgrounds(
.map(|(&node, style)| (node, PrintEconomyStyleSnapshot::apply(style)))
.collect::<Vec<_>>();
let result = paint_prepared_region_with_scroll_with_print_economy(
- tree, prepared, resources, scroll, region,
+ tree,
+ prepared,
+ resources,
+ scroll,
+ region,
+ canvas_surfaces,
)
.and_then(|pixmap| pixmap.encode_png().map_err(|_| CaptureError::EncodeFailed));
for (node, snapshot) in snapshots {
@@ -8689,6 +8888,122 @@ fn length_to_px(len: &str, viewport_width: f32) -> Option<f32> {
num(&t)
}
+fn paint_canvas_surface(
+ surface: CanvasSurface<'_>,
+ rect: &crate::Rect,
+ visible_rect: &crate::Rect,
+ object_fit: crate::ObjectFit,
+ object_position: crate::ObjectPosition,
+ pixmap: &mut Pixmap,
+ clip_radius: crate::ResolvedBorderRadii,
+ extra_clip: Option<&tiny_skia::Mask>,
+) -> bool {
+ if surface.width == 0
+ || surface.height == 0
+ || rect.width <= 0.0
+ || rect.height <= 0.0
+ || !rect_intersects_paint_surface(visible_rect, pixmap, 1.0)
+ {
+ return false;
+ }
+
+ // Canvas ImageData is straight-alpha RGBA; tiny-skia consumes
+ // premultiplied RGBA. Convert once per actual canvas paint while borrowing
+ // the live V8 backing directly—there is no JS-to-Rust surface copy on each
+ // Canvas2D operation.
+ let mut premultiplied = surface.rgba.to_vec();
+ for pixel in premultiplied.chunks_exact_mut(4) {
+ let alpha = pixel[3] as u32;
+ pixel[0] = ((pixel[0] as u32 * alpha + 127) / 255) as u8;
+ pixel[1] = ((pixel[1] as u32 * alpha + 127) / 255) as u8;
+ pixel[2] = ((pixel[2] as u32 * alpha + 127) / 255) as u8;
+ }
+ let Some(content) = tiny_skia::PixmapRef::from_bytes(
+ &premultiplied,
+ surface.width,
+ surface.height,
+ ) else {
+ return false;
+ };
+
+ let dest = object_fit_dest_positioned(
+ rect,
+ surface.width as f32,
+ surface.height as f32,
+ object_fit,
+ object_position,
+ );
+ if dest.width <= 0.0 || dest.height <= 0.0 {
+ return false;
+ }
+
+ let has_radius = !clip_radius.is_zero();
+ let needs_box_clip = has_radius
+ || dest.width > visible_rect.width + 0.5
+ || dest.height > visible_rect.height + 0.5
+ || dest.x < visible_rect.x - 0.5
+ || dest.y < visible_rect.y - 0.5;
+ let mut clip = extra_clip.cloned();
+ if needs_box_clip {
+ let path = if has_radius {
+ rounded_rect_path_radii(
+ visible_rect.x,
+ visible_rect.y,
+ visible_rect.width,
+ visible_rect.height,
+ clip_radius,
+ )
+ } else {
+ Rect::from_xywh(
+ visible_rect.x,
+ visible_rect.y,
+ visible_rect.width,
+ visible_rect.height,
+ )
+ .and_then(|rect| {
+ let mut builder = PathBuilder::new();
+ builder.push_rect(rect);
+ builder.finish()
+ })
+ };
+ match (clip.as_mut(), path) {
+ (Some(mask), Some(path)) => {
+ mask.intersect_path(&path, FillRule::Winding, true, Transform::identity())
+ }
+ (None, _) => {
+ clip = rounded_box_clip_mask_radii(
+ pixmap.width(),
+ pixmap.height(),
+ visible_rect,
+ clip_radius,
+ );
+ }
+ _ => {}
+ }
+ }
+
+ let transform = Transform::from_row(
+ dest.width / surface.width as f32,
+ 0.0,
+ 0.0,
+ dest.height / surface.height as f32,
+ dest.x,
+ dest.y,
+ );
+ pixmap.draw_pixmap(
+ 0,
+ 0,
+ content,
+ &tiny_skia::PixmapPaint {
+ quality: FilterQuality::Bilinear,
+ ..tiny_skia::PixmapPaint::default()
+ },
+ transform,
+ clip.as_ref(),
+ );
+ true
+}
+
fn paint_image(
src: &str,
base_url: Option<&str>,