forked from flutter/flutter
-
Notifications
You must be signed in to change notification settings - Fork 7
/
bitmap_canvas.dart
759 lines (688 loc) · 25.3 KB
/
bitmap_canvas.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of engine;
/// A raw HTML canvas that is directly written to.
class BitmapCanvas extends EngineCanvas {
/// The rectangle positioned relative to the parent layer's coordinate
/// system's origin, within which this canvas paints.
///
/// Painting outside these bounds will result in cropping.
ui.Rect get bounds => _bounds;
set bounds(ui.Rect newValue) {
assert(newValue != null);
_bounds = newValue;
final int newCanvasPositionX = _bounds.left.floor() - kPaddingPixels;
final int newCanvasPositionY = _bounds.top.floor() - kPaddingPixels;
if (_canvasPositionX != newCanvasPositionX ||
_canvasPositionY != newCanvasPositionY) {
_canvasPositionX = newCanvasPositionX;
_canvasPositionY = newCanvasPositionY;
_updateRootElementTransform();
}
}
ui.Rect _bounds;
/// The amount of padding to add around the edges of this canvas to
/// ensure that anti-aliased arcs are not clipped.
static const int kPaddingPixels = 1;
@override
final html.Element rootElement = html.Element.tag('flt-canvas');
final _CanvasPool _canvasPool;
/// The size of the paint [bounds].
ui.Size get size => _bounds.size;
/// The last paragraph style is cached to optimize the case where the style
/// hasn't changed.
ParagraphGeometricStyle _cachedLastStyle;
/// List of extra sibling elements created for paragraphs and clipping.
final List<html.Element> _children = <html.Element>[];
/// The number of pixels along the width of the bitmap that the canvas element
/// renders into.
///
/// These pixels are different from the logical CSS pixels. Here a pixel
/// literally means 1 point with a RGBA color.
final int _widthInBitmapPixels;
/// The number of pixels along the width of the bitmap that the canvas element
/// renders into.
///
/// These pixels are different from the logical CSS pixels. Here a pixel
/// literally means 1 point with a RGBA color.
final int _heightInBitmapPixels;
/// The number of pixels in the bitmap that the canvas element renders into.
///
/// These pixels are different from the logical CSS pixels. Here a pixel
/// literally means 1 point with a RGBA color.
int get bitmapPixelCount => _widthInBitmapPixels * _heightInBitmapPixels;
int _saveCount = 0;
/// Keeps track of what device pixel ratio was used when this [BitmapCanvas]
/// was created.
final double _devicePixelRatio = EngineWindow.browserDevicePixelRatio;
// Compensation for [_initializeViewport] snapping canvas position to 1 pixel.
int _canvasPositionX, _canvasPositionY;
// Indicates the instructions following drawImage or drawParagraph that
// a child element was created to paint.
// TODO(flutter_web): When childElements are created by
// drawImage/drawParagraph commands, compositing order is not correctly
// handled when we interleave these with other paint commands.
// To solve this, recording canvas will have to check the paint queue
// and send a hint to EngineCanvas that additional canvas layers need
// to be used to composite correctly. In practice this is very rare
// with Widgets but CustomPainter(s) can hit this code path.
bool _childOverdraw = false;
/// Allocates a canvas with enough memory to paint a picture within the given
/// [bounds].
///
/// This canvas can be reused by pictures with different paint bounds as long
/// as the [Rect.size] of the bounds fully fit within the size used to
/// initialize this canvas.
BitmapCanvas(this._bounds)
: assert(_bounds != null),
_widthInBitmapPixels = _widthToPhysical(_bounds.width),
_heightInBitmapPixels = _heightToPhysical(_bounds.height),
_canvasPool = _CanvasPool(_widthToPhysical(_bounds.width),
_heightToPhysical(_bounds.height)) {
rootElement.style.position = 'absolute';
// Adds one extra pixel to the requested size. This is to compensate for
// _initializeViewport() snapping canvas position to 1 pixel, causing
// painting to overflow by at most 1 pixel.
_canvasPositionX = _bounds.left.floor() - kPaddingPixels;
_canvasPositionY = _bounds.top.floor() - kPaddingPixels;
_updateRootElementTransform();
_canvasPool.allocateCanvas(rootElement);
_setupInitialTransform();
}
void _updateRootElementTransform() {
// Flutter emits paint operations positioned relative to the parent layer's
// coordinate system. However, canvas' coordinate system's origin is always
// in the top-left corner of the canvas. We therefore need to inject an
// initial translation so the paint operations are positioned as expected.
//
// The flooring of the value is to ensure that canvas' top-left corner
// lands on the physical pixel. TODO: !This is not accurate if there are
// transforms higher up in the stack.
rootElement.style.transform =
'translate(${_canvasPositionX}px, ${_canvasPositionY}px)';
}
void _setupInitialTransform() {
final double canvasPositionCorrectionX = _bounds.left -
BitmapCanvas.kPaddingPixels -
_canvasPositionX.toDouble();
final double canvasPositionCorrectionY =
_bounds.top - BitmapCanvas.kPaddingPixels - _canvasPositionY.toDouble();
// This compensates for the translate on the `rootElement`.
_canvasPool.initialTransform = ui.Offset(
-_bounds.left + canvasPositionCorrectionX + BitmapCanvas.kPaddingPixels,
-_bounds.top + canvasPositionCorrectionY + BitmapCanvas.kPaddingPixels,
);
}
static int _widthToPhysical(double width) {
final double boundsWidth = width + 1;
return (boundsWidth * EngineWindow.browserDevicePixelRatio).ceil() +
2 * kPaddingPixels;
}
static int _heightToPhysical(double height) {
final double boundsHeight = height + 1;
return (boundsHeight * EngineWindow.browserDevicePixelRatio).ceil() +
2 * kPaddingPixels;
}
// Used by picture to assess if canvas is large enough to reuse as is.
bool doesFitBounds(ui.Rect newBounds) {
assert(newBounds != null);
return _widthInBitmapPixels >= _widthToPhysical(newBounds.width) &&
_heightInBitmapPixels >= _heightToPhysical(newBounds.height);
}
@override
void dispose() {
_canvasPool.dispose();
}
/// Prepare to reuse this canvas by clearing it's current contents.
@override
void clear() {
_canvasPool.clear();
final int len = _children.length;
for (int i = 0; i < len; i++) {
_children[i].remove();
}
_children.clear();
_cachedLastStyle = null;
_setupInitialTransform();
}
/// Checks whether this [BitmapCanvas] can still be recycled and reused.
///
/// See also:
///
/// * [PersistedStandardPicture._applyBitmapPaint] which uses this method to
/// decide whether to reuse this canvas or not.
/// * [PersistedStandardPicture._recycleCanvas] which also uses this method
/// for the same reason.
bool isReusable() {
return _devicePixelRatio == EngineWindow.browserDevicePixelRatio;
}
/// Returns a data URI containing a representation of the image in this
/// canvas.
String toDataUrl() {
return _canvasPool.toDataUrl();
}
/// Sets the global paint styles to correspond to [paint].
void _applyPaint(SurfacePaintData paint) {
ContextStateHandle contextHandle = _canvasPool.contextHandle;
contextHandle
..lineWidth = paint.strokeWidth ?? 1.0
..blendMode = paint.blendMode
..strokeCap = paint.strokeCap
..strokeJoin = paint.strokeJoin
..filter = _maskFilterToCss(paint.maskFilter);
if (paint.shader != null) {
final EngineGradient engineShader = paint.shader;
final Object paintStyle =
engineShader.createPaintStyle(_canvasPool.context);
contextHandle.fillStyle = paintStyle;
contextHandle.strokeStyle = paintStyle;
} else if (paint.color != null) {
final String colorString = paint.color.toCssString();
contextHandle.fillStyle = colorString;
contextHandle.strokeStyle = colorString;
} else {
contextHandle.fillStyle = '';
contextHandle.strokeStyle = '';
}
}
@override
int save() {
_canvasPool.save();
return _saveCount++;
}
void saveLayer(ui.Rect bounds, ui.Paint paint) {
save();
}
@override
void restore() {
_canvasPool.restore();
_saveCount--;
_cachedLastStyle = null;
}
// TODO(yjbanov): not sure what this is attempting to do, but it is probably
// wrong because some clips and transforms are expressed using
// HTML DOM elements.
void restoreToCount(int count) {
assert(_saveCount >= count);
final int restores = _saveCount - count;
for (int i = 0; i < restores; i++) {
_canvasPool.restore();
}
_saveCount = count;
}
@override
void translate(double dx, double dy) {
_canvasPool.translate(dx, dy);
}
@override
void scale(double sx, double sy) {
_canvasPool.scale(sx, sy);
}
@override
void rotate(double radians) {
_canvasPool.rotate(radians);
}
@override
void skew(double sx, double sy) {
_canvasPool.skew(sx, sy);
}
@override
void transform(Float64List matrix4) {
_canvasPool.transform(matrix4);
}
@override
void clipRect(ui.Rect rect) {
_canvasPool.clipRect(rect);
}
@override
void clipRRect(ui.RRect rrect) {
_canvasPool.clipRRect(rrect);
}
@override
void clipPath(ui.Path path) {
_canvasPool.clipPath(path);
}
@override
void drawColor(ui.Color color, ui.BlendMode blendMode) {
_canvasPool.drawColor(color, blendMode);
}
@override
void drawLine(ui.Offset p1, ui.Offset p2, SurfacePaintData paint) {
_applyPaint(paint);
_canvasPool.strokeLine(p1, p2);
}
@override
void drawPaint(SurfacePaintData paint) {
_applyPaint(paint);
_canvasPool.fill();
}
@override
void drawRect(ui.Rect rect, SurfacePaintData paint) {
_applyPaint(paint);
_canvasPool.drawRect(rect, paint.style);
}
@override
void drawRRect(ui.RRect rrect, SurfacePaintData paint) {
_applyPaint(paint);
_canvasPool.drawRRect(rrect, paint.style);
}
@override
void drawDRRect(ui.RRect outer, ui.RRect inner, SurfacePaintData paint) {
_applyPaint(paint);
_canvasPool.drawDRRect(outer, inner, paint.style);
}
@override
void drawOval(ui.Rect rect, SurfacePaintData paint) {
_applyPaint(paint);
_canvasPool.drawOval(rect, paint.style);
}
@override
void drawCircle(ui.Offset c, double radius, SurfacePaintData paint) {
_applyPaint(paint);
_canvasPool.drawCircle(c, radius, paint.style);
}
@override
void drawPath(ui.Path path, SurfacePaintData paint) {
_applyPaint(paint);
_canvasPool.drawPath(path, paint.style);
}
@override
void drawShadow(ui.Path path, ui.Color color, double elevation,
bool transparentOccluder) {
_canvasPool.drawShadow(path, color, elevation, transparentOccluder);
}
@override
void drawImage(ui.Image image, ui.Offset p, SurfacePaintData paint) {
//_applyPaint(paint);
final HtmlImage htmlImage = image;
final html.ImageElement imgElement = htmlImage.cloneImageElement();
String blendMode = _stringForBlendMode(paint.blendMode);
imgElement.style.mixBlendMode = blendMode;
_drawImage(imgElement, p);
_childOverdraw = true;
_canvasPool.allocateExtraCanvas();
}
void _drawImage(html.ImageElement imgElement, ui.Offset p) {
if (_canvasPool.isClipped) {
final List<html.Element> clipElements = _clipContent(
_canvasPool._clipStack, imgElement, p, _canvasPool.currentTransform);
for (html.Element clipElement in clipElements) {
rootElement.append(clipElement);
_children.add(clipElement);
}
} else {
final String cssTransform = matrix4ToCssTransform3d(
transformWithOffset(_canvasPool.currentTransform, p));
imgElement.style
..transformOrigin = '0 0 0'
..transform = cssTransform;
rootElement.append(imgElement);
_children.add(imgElement);
}
}
@override
void drawImageRect(
ui.Image image, ui.Rect src, ui.Rect dst, SurfacePaintData paint) {
final HtmlImage htmlImage = image;
final bool requiresClipping = src.left != 0 ||
src.top != 0 ||
src.width != image.width ||
src.height != image.height;
if (dst.width == image.width &&
dst.height == image.height &&
!requiresClipping) {
drawImage(image, dst.topLeft, paint);
} else {
_applyPaint(paint);
final html.Element imgElement = htmlImage.cloneImageElement();
final ui.BlendMode blendMode = paint.blendMode;
imgElement.style.mixBlendMode = _stringForBlendMode(blendMode);
if (requiresClipping) {
save();
clipRect(dst);
}
double targetLeft = dst.left;
double targetTop = dst.top;
if (requiresClipping) {
if (src.width != image.width) {
double leftMargin = -src.left * (dst.width / src.width);
targetLeft += leftMargin;
}
if (src.height != image.height) {
double topMargin = -src.top * (dst.height / src.height);
targetTop += topMargin;
}
}
_drawImage(imgElement, ui.Offset(targetLeft, targetTop));
// To scale set width / height on destination image.
// For clipping we need to scale according to
// clipped-width/full image width and shift it according to left/top of
// source rectangle.
double targetWidth = dst.width;
double targetHeight = dst.height;
if (requiresClipping) {
targetWidth *= image.width / src.width;
targetHeight *= image.height / src.height;
}
final html.CssStyleDeclaration imageStyle = imgElement.style;
imageStyle
..width = '${targetWidth.toStringAsFixed(2)}px'
..height = '${targetHeight.toStringAsFixed(2)}px';
if (requiresClipping) {
restore();
}
_canvasPool.allocateExtraCanvas();
}
_childOverdraw = true;
}
void _drawTextLine(
ParagraphGeometricStyle style,
EngineLineMetrics line,
double x,
double y,
) {
html.CanvasRenderingContext2D ctx = _canvasPool.context;
final double letterSpacing = style.letterSpacing;
if (letterSpacing == null || letterSpacing == 0.0) {
ctx.fillText(line.text, x, y);
} else {
// When letter-spacing is set, we go through a more expensive code path
// that renders each character separately with the correct spacing
// between them.
//
// We are drawing letter spacing like the web does it, by adding the
// spacing after each letter. This is different from Flutter which puts
// the spacing around each letter i.e. for a 10px letter spacing, Flutter
// would put 5px before each letter and 5px after it, but on the web, we
// put no spacing before the letter and 10px after it. This is how the DOM
// does it.
final int len = line.text.length;
for (int i = 0; i < len; i++) {
final String char = line.text[i];
ctx.fillText(char, x, y);
x += letterSpacing + ctx.measureText(char).width;
}
}
}
@override
void drawParagraph(EngineParagraph paragraph, ui.Offset offset) {
assert(paragraph._isLaidOut);
html.CanvasRenderingContext2D ctx = _canvasPool.context;
final ParagraphGeometricStyle style = paragraph._geometricStyle;
if (paragraph._drawOnCanvas && _childOverdraw == false) {
final List<EngineLineMetrics> lines = paragraph._measurementResult.lines;
final SurfacePaintData backgroundPaint = paragraph._background?.paintData;
if (backgroundPaint != null) {
final ui.Rect rect = ui.Rect.fromLTWH(
offset.dx, offset.dy, paragraph.width, paragraph.height);
drawRect(rect, backgroundPaint);
}
if (style != _cachedLastStyle) {
ctx.font = style.cssFontString;
_cachedLastStyle = style;
}
_applyPaint(paragraph._paint.paintData);
final double x = offset.dx + paragraph._alignOffset;
double y = offset.dy + paragraph.alphabeticBaseline;
final int len = lines.length;
for (int i = 0; i < len; i++) {
_drawTextLine(style, lines[i], x, y);
y += paragraph._lineHeight;
}
return;
}
final html.Element paragraphElement =
_drawParagraphElement(paragraph, offset);
if (_canvasPool.isClipped) {
final List<html.Element> clipElements = _clipContent(
_canvasPool._clipStack,
paragraphElement,
offset,
_canvasPool.currentTransform);
for (html.Element clipElement in clipElements) {
rootElement.append(clipElement);
_children.add(clipElement);
}
} else {
final String cssTransform = matrix4ToCssTransform3d(
transformWithOffset(_canvasPool.currentTransform, offset));
paragraphElement.style
..transformOrigin = '0 0 0'
..transform = cssTransform;
rootElement.append(paragraphElement);
}
_children.add(paragraphElement);
}
/// Paints the [picture] into this canvas.
void drawPicture(ui.Picture picture) {
final EnginePicture enginePicture = picture;
enginePicture.recordingCanvas.apply(this);
}
/// Draws vertices on a gl context.
///
/// If both colors and textures is specified in paint data,
/// for [BlendMode.source] we skip colors and use textures,
/// for [BlendMode.dst] we only use colors and ignore textures.
/// We also skip paint shader when no texture is specified.
///
/// If no colors or textures are specified, stroke hairlines with
/// [Paint.color].
///
/// If colors is specified, convert colors to premultiplied (alpha) colors
/// and use a SkTriColorShader to render.
@override
void drawVertices(
ui.Vertices vertices, ui.BlendMode blendMode, SurfacePaintData paint) {
// TODO(flutter_web): Implement shaders for [Paint.shader] and
// blendMode. https://github.com/flutter/flutter/issues/40096
// Move rendering to OffscreenCanvas so that transform is preserved
// as well.
assert(paint.shader == null,
'Linear/Radial/SweepGradient and ImageShader not supported yet');
final Int32List colors = vertices.colors;
final ui.VertexMode mode = vertices.mode;
html.CanvasRenderingContext2D ctx = _canvasPool.context;
if (colors == null) {
final Float32List positions = mode == ui.VertexMode.triangles
? vertices.positions
: _convertVertexPositions(mode, vertices.positions);
// Draw hairline for vertices if no vertex colors are specified.
save();
final ui.Color color = paint.color ?? ui.Color(0xFF000000);
_canvasPool.contextHandle
..fillStyle = null
..strokeStyle = color.toCssString();
_glRenderer.drawHairline(ctx, positions);
restore();
return;
}
_glRenderer.drawVertices(ctx, _widthInBitmapPixels, _heightInBitmapPixels,
_canvasPool.currentTransform, vertices, blendMode, paint);
}
@override
void endOfPaint() {
assert(_saveCount == 0);
_canvasPool.endOfPaint();
}
}
String _stringForBlendMode(ui.BlendMode blendMode) {
if (blendMode == null) {
return null;
}
switch (blendMode) {
case ui.BlendMode.srcOver:
return 'source-over';
case ui.BlendMode.srcIn:
return 'source-in';
case ui.BlendMode.srcOut:
return 'source-out';
case ui.BlendMode.srcATop:
return 'source-atop';
case ui.BlendMode.dstOver:
return 'destination-over';
case ui.BlendMode.dstIn:
return 'destination-in';
case ui.BlendMode.dstOut:
return 'destination-out';
case ui.BlendMode.dstATop:
return 'destination-atop';
case ui.BlendMode.plus:
return 'lighten';
case ui.BlendMode.src:
return 'copy';
case ui.BlendMode.xor:
return 'xor';
case ui.BlendMode.multiply:
// Falling back to multiply, ignoring alpha channel.
// TODO(flutter_web): only used for debug, find better fallback for web.
case ui.BlendMode.modulate:
return 'multiply';
case ui.BlendMode.screen:
return 'screen';
case ui.BlendMode.overlay:
return 'overlay';
case ui.BlendMode.darken:
return 'darken';
case ui.BlendMode.lighten:
return 'lighten';
case ui.BlendMode.colorDodge:
return 'color-dodge';
case ui.BlendMode.colorBurn:
return 'color-burn';
case ui.BlendMode.hardLight:
return 'hard-light';
case ui.BlendMode.softLight:
return 'soft-light';
case ui.BlendMode.difference:
return 'difference';
case ui.BlendMode.exclusion:
return 'exclusion';
case ui.BlendMode.hue:
return 'hue';
case ui.BlendMode.saturation:
return 'saturation';
case ui.BlendMode.color:
return 'color';
case ui.BlendMode.luminosity:
return 'luminosity';
default:
throw UnimplementedError(
'Flutter Web does not support the blend mode: $blendMode');
}
}
String _stringForStrokeCap(ui.StrokeCap strokeCap) {
if (strokeCap == null) {
return null;
}
switch (strokeCap) {
case ui.StrokeCap.butt:
return 'butt';
case ui.StrokeCap.round:
return 'round';
case ui.StrokeCap.square:
default:
return 'square';
}
}
String _stringForStrokeJoin(ui.StrokeJoin strokeJoin) {
assert(strokeJoin != null);
switch (strokeJoin) {
case ui.StrokeJoin.round:
return 'round';
case ui.StrokeJoin.bevel:
return 'bevel';
case ui.StrokeJoin.miter:
default:
return 'miter';
}
}
/// Clips the content element against a stack of clip operations and returns
/// root of a tree that contains content node.
///
/// The stack of clipping rectangles generate an element that either uses
/// overflow:hidden with bounds to clip child or sets a clip-path to clip
/// it's contents. The clipping rectangles are nested and returned together
/// with a list of svg elements that provide clip-paths.
List<html.Element> _clipContent(List<_SaveClipEntry> clipStack,
html.HtmlElement content, ui.Offset offset, Matrix4 currentTransform) {
html.Element root, curElement;
final List<html.Element> clipDefs = <html.Element>[];
final int len = clipStack.length;
for (int clipIndex = 0; clipIndex < len; clipIndex++) {
final _SaveClipEntry entry = clipStack[clipIndex];
final html.HtmlElement newElement = html.DivElement();
if (root == null) {
root = newElement;
} else {
domRenderer.append(curElement, newElement);
}
curElement = newElement;
final ui.Rect rect = entry.rect;
Matrix4 newClipTransform = entry.currentTransform;
if (rect != null) {
final double clipOffsetX = rect.left;
final double clipOffsetY = rect.top;
newClipTransform = newClipTransform.clone()
..translate(clipOffsetX, clipOffsetY);
curElement.style
..overflow = 'hidden'
..transform = matrix4ToCssTransform3d(newClipTransform)
..transformOrigin = '0 0 0'
..width = '${rect.right - clipOffsetX}px'
..height = '${rect.bottom - clipOffsetY}px';
} else if (entry.rrect != null) {
final ui.RRect roundRect = entry.rrect;
final String borderRadius =
'${roundRect.tlRadiusX}px ${roundRect.trRadiusX}px '
'${roundRect.brRadiusX}px ${roundRect.blRadiusX}px';
final double clipOffsetX = roundRect.left;
final double clipOffsetY = roundRect.top;
newClipTransform = newClipTransform.clone()
..translate(clipOffsetX, clipOffsetY);
curElement.style
..borderRadius = borderRadius
..overflow = 'hidden'
..transform = matrix4ToCssTransform3d(newClipTransform)
..transformOrigin = '0 0 0'
..width = '${roundRect.right - clipOffsetX}px'
..height = '${roundRect.bottom - clipOffsetY}px';
} else if (entry.path != null) {
curElement.style.transform = matrix4ToCssTransform(newClipTransform);
final String svgClipPath = _pathToSvgClipPath(entry.path);
final html.Element clipElement =
html.Element.html(svgClipPath, treeSanitizer: _NullTreeSanitizer());
domRenderer.setElementStyle(
curElement, 'clip-path', 'url(#svgClip$_clipIdCounter)');
domRenderer.setElementStyle(
curElement, '-webkit-clip-path', 'url(#svgClip$_clipIdCounter)');
clipDefs.add(clipElement);
}
// Reverse the transform of the clipping element so children can use
// effective transform to render.
// TODO(flutter_web): When we have more than a single clip element,
// reduce number of div nodes by merging (multiplying transforms).
final html.Element reverseTransformDiv = html.DivElement();
reverseTransformDiv.style
..transform =
_cssTransformAtOffset(newClipTransform.clone()..invert(), 0, 0)
..transformOrigin = '0 0 0';
curElement.append(reverseTransformDiv);
curElement = reverseTransformDiv;
}
root.style.position = 'absolute';
domRenderer.append(curElement, content);
content.style
..transformOrigin = '0 0 0'
..transform = _cssTransformAtOffset(currentTransform, offset.dx, offset.dy);
return <html.Element>[root]..addAll(clipDefs);
}
String _cssTransformAtOffset(
Matrix4 transform, double offsetX, double offsetY) {
return matrix4ToCssTransform3d(
transformWithOffset(transform, ui.Offset(offsetX, offsetY)));
}
String _maskFilterToCss(ui.MaskFilter maskFilter) {
if (maskFilter == null) return 'none';
return 'blur(${maskFilter.webOnlySigma}px)';
}