Skip to content

Commit f0add0e

Browse files
[web] Recreate canvas and context on CkOffscreenSurface resize to fix WebGL clipping (flutter#192769)
### Description Fixes part of flutter#182476 When exporting large images via `Picture.toImage()`, Chrome may silently clamp the physical WebGL drawing buffer during in-place canvas resizing, leaving pixels outside the clamped area unbacked and producing transparent strips. This PR updates `CkOffscreenSurface` to detect when the drawing buffer is clamped on resize and acquire a fresh offscreen canvas to allocate the buffer cleanly upfront. If the requested size exceeds what the browser/GPU can support even after recreation, an `UnsupportedError` is thrown rather than silently returning clipped pixels. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant in-code documentation (doc comments with `///`). - [x] If this PR introduces a new feature or capability, I created and linked a website documentation issue or PR in [flutter/website] (or verified none is needed). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [flutter/website]: https://github.com/flutter/website [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
1 parent b78f68c commit f0add0e

3 files changed

Lines changed: 986 additions & 3 deletions

File tree

‎engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/surface.dart‎

Lines changed: 180 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import 'dart:async';
66
import 'dart:js_interop';
7+
import 'dart:math' as math;
78
import 'dart:typed_data';
89

910
import 'package:meta/meta.dart';
@@ -99,10 +100,19 @@ abstract class CkSurface extends Surface {
99100
/// The underlying Skia graphics context.
100101
SkGrContext? _grContext;
101102

103+
bool _isDisposed = false;
104+
102105
/// Handles the context lost event by acquiring a new canvas and recreating
103106
/// the graphics context.
104107
void onContextLost() {
105-
_handledContextLostEvent?.complete();
108+
if (_isDisposed) {
109+
return;
110+
}
111+
if (_handledContextLostEvent case final Completer<void> completer) {
112+
if (!completer.isCompleted) {
113+
completer.complete();
114+
}
115+
}
106116
final DomEventTarget newCanvas = _canvasProvider.acquireCanvas(
107117
_currentSize,
108118
onContextLost: onContextLost,
@@ -198,19 +208,49 @@ abstract class CkSurface extends Surface {
198208
@override
199209
void setSize(BitmapSize size) {
200210
final double devicePixelRatio = EngineFlutterDisplay.instance.devicePixelRatio;
211+
// A zero-sized canvas cannot back a WebGL SkSurface and would force the
212+
// surface into a permanent software fallback, so never go below 1x1.
213+
final clampedSize = BitmapSize(math.max(1, size.width), math.max(1, size.height));
201214
if (_skSurface != null &&
202-
_currentSize == size &&
215+
_currentSize == clampedSize &&
203216
devicePixelRatio == _currentDevicePixelRatio) {
204217
return;
205218
}
219+
final BitmapSize previousSize = _currentSize;
220+
final double previousDevicePixelRatio = _currentDevicePixelRatio;
206221
_currentDevicePixelRatio = devicePixelRatio;
207-
_currentSize = size;
222+
_currentSize = clampedSize;
223+
try {
224+
_resizeCanvas(clampedSize, previousSize);
225+
} catch (_) {
226+
// Keep the recorded state in sync with the surface that is still in use.
227+
_currentSize = previousSize;
228+
_currentDevicePixelRatio = previousDevicePixelRatio;
229+
rethrow;
230+
}
231+
}
232+
233+
/// Resizes the underlying canvas to [size] and recreates the Skia surface.
234+
///
235+
/// [previousSize] is the size the surface had before this call. If this
236+
/// method throws, the surface must be left usable at [previousSize].
237+
///
238+
/// Subclasses in this library may override this if their underlying canvas
239+
/// type requires re-allocation or context recreation instead of in-place
240+
/// dimension updates.
241+
void _resizeCanvas(BitmapSize size, BitmapSize previousSize) {
208242
_canvasProvider.resizeCanvas(canvas, size);
209243
_recreateSkSurface();
210244
}
211245

212246
@override
213247
Future<void> recreateContextForCanvas(DomEventTarget newCanvas) async {
248+
_adoptCanvas(newCanvas);
249+
}
250+
251+
/// Switches this surface to [newCanvas] and synchronously recreates the
252+
/// GrContext and Skia surface for it at [_currentSize].
253+
void _adoptCanvas(DomEventTarget newCanvas) {
214254
// The old Skia surface is now invalid and should be disposed.
215255
_skSurface?.dispose();
216256
_skSurface = null;
@@ -225,6 +265,7 @@ abstract class CkSurface extends Surface {
225265

226266
@override
227267
void dispose() {
268+
_isDisposed = true;
228269
_skSurface?.dispose();
229270
_skSurface = null;
230271
}
@@ -378,12 +419,148 @@ class CkOffscreenSurface extends CkSurface implements OffscreenSurface {
378419
// Do not attach the OffscreenCanvas to the DOM.
379420
}
380421

422+
/// Resizes the offscreen canvas to [size], preserving fast in-place resizing
423+
/// unless the browser's physical WebGL drawing buffer is clamped.
424+
///
425+
/// The requested dimensions are first validated against the context's
426+
/// `GL_MAX_TEXTURE_SIZE`. If either dimension exceeds it, an
427+
/// [UnsupportedError] is thrown before the canvas is touched, so the
428+
/// existing surface remains usable at its previous size.
429+
///
430+
/// For standard sizes, modifying `canvas.width` and `canvas.height` in-place
431+
/// updates the drawing buffer without recreating the WebGL context or
432+
/// churning GPU resources.
433+
///
434+
/// However, when an existing context is resized, Chromium caps the drawing
435+
/// buffer's area at 5760x5760 and scales both dimensions down to fit (e.g.
436+
/// 4960x7016 becomes 4843x6850, see
437+
/// https://github.com/flutter/flutter/issues/182476). A newly created context
438+
/// is not subject to this cap, although other browser or GPU limits may still
439+
/// give it a smaller buffer, which is checked below.
440+
///
441+
/// When a drawing buffer clamp is detected, the old canvas is replaced with a
442+
/// brand-new [DomOffscreenCanvas] and a fresh WebGL context (see
443+
/// [_replaceCanvas]), allowing the browser to allocate the full buffer
444+
/// upfront. A context that is already lost (e.g. its `webglcontextlost`
445+
/// event is still pending) reports a zero-sized drawing buffer and is
446+
/// recovered the same way.
447+
///
448+
/// If the fresh context's drawing buffer is still smaller than [size], the
449+
/// surface is moved to another fresh canvas at [previousSize] and an
450+
/// [UnsupportedError] is thrown instead of silently rendering clipped
451+
/// output.
452+
@override
453+
void _resizeCanvas(BitmapSize size, BitmapSize previousSize) {
454+
if (!supportsWebGl) {
455+
super._resizeCanvas(size, previousSize);
456+
return;
457+
}
458+
459+
final WebGLContext gl = (canvas as DomOffscreenCanvas).getGlContext(webGLVersion);
460+
// A lost context reports no parameters; skip validation and let the
461+
// zero-sized drawing buffer below route to recovery on a fresh canvas.
462+
if (!gl.isContextLost()) {
463+
final int maxTextureSize = gl.getParameter(gl.maxTextureSize);
464+
if (size.width > maxTextureSize || size.height > maxTextureSize) {
465+
throw UnsupportedError(
466+
'Requested dimensions ${size.width}x${size.height} exceed '
467+
'GL_MAX_TEXTURE_SIZE ($maxTextureSize).',
468+
);
469+
}
470+
}
471+
472+
_canvasProvider.resizeCanvas(canvas, size);
473+
474+
if (gl.drawingBufferWidth >= size.width && gl.drawingBufferHeight >= size.height) {
475+
_recreateSkSurface();
476+
return;
477+
}
478+
479+
_replaceCanvas(size);
480+
481+
// If creating the new context failed, the surface has fallen back to
482+
// software rendering, which has no drawing buffer to check.
483+
if (supportsWebGl) {
484+
final WebGLContext newGl = (canvas as DomOffscreenCanvas).getGlContext(webGLVersion);
485+
final int bufferWidth = newGl.drawingBufferWidth;
486+
final int bufferHeight = newGl.drawingBufferHeight;
487+
if (bufferWidth < size.width || bufferHeight < size.height) {
488+
// Use another fresh canvas rather than shrinking this one in place, so
489+
// that a previous size above the resize cap is not clamped either.
490+
_replaceCanvas(previousSize);
491+
throw UnsupportedError(
492+
'Requested dimensions ${size.width}x${size.height} exceed the WebGL '
493+
'drawing buffer allocated by the browser (${bufferWidth}x$bufferHeight).',
494+
);
495+
}
496+
}
497+
}
498+
499+
/// Releases the current canvas, explicitly loses its WebGL context so the
500+
/// browser frees the context slot immediately, and tears down the Skia
501+
/// objects bound to it.
502+
void _releaseCanvasAndContext() {
503+
final offscreenCanvas = canvas as DomOffscreenCanvas;
504+
// Release the canvas first so that its `webglcontextlost` listener is
505+
// removed and [onContextLost] does not fire for the deliberate loss below.
506+
_canvasProvider.releaseCanvas(offscreenCanvas);
507+
if (supportsWebGl) {
508+
final WebGLContext gl = offscreenCanvas.getGlContext(webGLVersion);
509+
// An already-lost context holds no slot to free and exposes no
510+
// extensions.
511+
if (!gl.isContextLost()) {
512+
gl.loseContextExtension.loseContext();
513+
}
514+
}
515+
516+
// Unlike `_adoptCanvas`, which only drops its references,
517+
// dispose the SkSurface before abandoning and deleting the GrContext so the
518+
// Skia objects bound to the old context are freed now.
519+
_skSurface?.dispose();
520+
_skSurface = null;
521+
_grContext?.releaseResourcesAndAbandonContext();
522+
_grContext?.delete();
523+
_grContext = null;
524+
}
525+
526+
/// Replaces the current canvas with a new one of [size] and attempts to
527+
/// create a fresh WebGL context for it, falling back to software rendering
528+
/// if that fails.
529+
///
530+
/// The old canvas and its context are torn down by
531+
/// [_releaseCanvasAndContext] before the new canvas is acquired.
532+
///
533+
/// This also records [size] as the current size, because the new Skia
534+
/// surface is created at [_currentSize].
535+
void _replaceCanvas(BitmapSize size) {
536+
_currentSize = size;
537+
_releaseCanvasAndContext();
538+
539+
final DomEventTarget newCanvas = _canvasProvider.acquireCanvas(
540+
size,
541+
onContextLost: onContextLost,
542+
);
543+
// Adopt the canvas synchronously so that the new GL context and Skia
544+
// objects are in place before the caller inspects the drawing buffer, and
545+
// so that resizing stays atomic with the render that follows it.
546+
_adoptCanvas(newCanvas);
547+
}
548+
381549
@override
382550
Future<void> triggerContextLoss() async {
383551
_handledContextLostEvent = Completer<void>();
384552
final WebGLContext gl = (canvas as DomOffscreenCanvas).getGlContext(webGLVersion);
385553
gl.loseContextExtension.loseContext();
386554
}
555+
556+
@override
557+
void dispose() {
558+
if (_isDisposed) {
559+
return;
560+
}
561+
_releaseCanvasAndContext();
562+
super.dispose();
563+
}
387564
}
388565

389566
/// The CanvasKit implementation of [OnscreenSurface].

‎engine/src/flutter/lib/web_ui/lib/src/engine/dom.dart‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,12 +1009,18 @@ DomHTMLCanvasElement createDomCanvasElement({int? width, int? height}) {
10091009
extension type WebGLContext._(JSObject _) implements JSObject {
10101010
external int getParameter(int value);
10111011

1012+
external int get drawingBufferWidth;
1013+
external int get drawingBufferHeight;
1014+
10121015
@JS('SAMPLES')
10131016
external int get samples;
10141017

10151018
@JS('STENCIL_BITS')
10161019
external int get stencilBits;
10171020

1021+
@JS('MAX_TEXTURE_SIZE')
1022+
external int get maxTextureSize;
1023+
10181024
external JSAny? getExtension(String name);
10191025

10201026
WebGLLoseContextExtension get loseContextExtension {

0 commit comments

Comments
 (0)