[web] use typed SVG API (flutter/engine#29481)

This commit is contained in:
Yegor
2021-11-23 15:57:18 -08:00
committed by GitHub
parent d755e4f9ad
commit 4a81b38f3a
11 changed files with 683 additions and 322 deletions

View File

@@ -29,6 +29,8 @@ import 'dart:js' as js;
import 'dart:js_util' as js_util;
// ignore: unused_import
import 'dart:math' as math;
// ignore: unused_import
import 'dart:svg' as svg;
import 'dart:typed_data';
import 'package:js/js.dart';
@@ -476,13 +478,6 @@ void _addUrlStrategyListener() {
});
}
/// Sanitizer used to convert const svg filter and clippath snippets to
/// SvgElement without sanitization.
class NullTreeSanitizer implements html.NodeTreeSanitizer {
@override
void sanitizeTree(html.Node node) {}
}
/// The shared instance of PlatformViewManager shared across the engine to handle
/// rendering of PlatformViews into the web app.
// TODO(dit): How to make this overridable from tests?

View File

@@ -899,7 +899,7 @@ class ContextStateHandle {
if (blendMode != _currentBlendMode) {
_currentBlendMode = blendMode;
context.globalCompositeOperation =
stringForBlendMode(blendMode) ?? 'source-over';
blendModeToCssMixBlendMode(blendMode) ?? 'source-over';
}
}

View File

@@ -4,10 +4,11 @@
import 'dart:html' as html;
import 'dart:math' as math;
import 'dart:svg' as svg;
import 'package:ui/ui.dart' as ui;
import '../../engine.dart' show NullTreeSanitizer, platformViewManager;
import '../../engine.dart' show platformViewManager;
import '../configuration.dart';
import '../html/path_to_svg_clip.dart';
import '../platform_views/slots.dart';
@@ -332,12 +333,13 @@ class HtmlViewEmbedder {
_svgPathDefs!.querySelector('#sk_path_defs')!;
_clipPathCount += 1;
final String clipId = 'svgClip$_clipPathCount';
final html.Node newClipPath = html.DocumentFragment.svg(
'<clipPath id="$clipId">'
'<path d="${path.toSvgString()}">'
'</path></clipPath>',
treeSanitizer: NullTreeSanitizer(),
final svg.ClipPathElement newClipPath = svg.ClipPathElement();
newClipPath.id = clipId;
newClipPath.append(
svg.PathElement()
..setAttribute('d', path.toSvgString()!)
);
pathDefs.append(newClipPath);
// Store the id of the node instead of [newClipPath] directly. For
// some reason, calling `newClipPath.remove()` doesn't remove it
@@ -351,11 +353,11 @@ class HtmlViewEmbedder {
_svgPathDefs!.querySelector('#sk_path_defs')!;
_clipPathCount += 1;
final String clipId = 'svgClip$_clipPathCount';
final html.Node newClipPath = html.DocumentFragment.svg(
'<clipPath id="$clipId">'
'<path d="${path.toSvgString()}">'
'</path></clipPath>',
treeSanitizer: NullTreeSanitizer(),
final svg.ClipPathElement newClipPath = svg.ClipPathElement();
newClipPath.id = clipId;
newClipPath.append(
svg.PathElement()
..setAttribute('d', path.toSvgString()!)
);
pathDefs.append(newClipPath);
// Store the id of the node instead of [newClipPath] directly. For
@@ -409,10 +411,8 @@ class HtmlViewEmbedder {
if (_svgPathDefs != null) {
return;
}
_svgPathDefs = html.Element.html(
'$kSvgResourceHeader<defs id="sk_path_defs"></defs></svg>',
treeSanitizer: NullTreeSanitizer(),
);
_svgPathDefs = kSvgResourceHeader.clone(false) as svg.SvgSvgElement;
_svgPathDefs!.append(svg.DefsElement()..id = 'sk_path_defs');
skiaSceneHost!.append(_svgPathDefs!);
}

View File

@@ -8,7 +8,6 @@ import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../../engine.dart' show NullTreeSanitizer;
import '../browser_detection.dart';
import '../canvas_pool.dart';
import '../canvaskit/color_filter.dart';
@@ -468,7 +467,7 @@ class BitmapCanvas extends EngineCanvas {
}
final ui.BlendMode? blendMode = paint.blendMode;
if (blendMode != null) {
element.style.mixBlendMode = stringForBlendMode(blendMode) ?? '';
element.style.mixBlendMode = blendModeToCssMixBlendMode(blendMode) ?? '';
}
// Switch to preferring DOM from now on, and close the current canvas.
_closeCurrentCanvas();
@@ -669,7 +668,7 @@ class BitmapCanvas extends EngineCanvas {
// No Blending, create an image by cloning original loaded image.
imgElement = _reuseOrCreateImage(htmlImage);
}
imgElement.style.mixBlendMode = stringForBlendMode(blendMode) ?? '';
imgElement.style.mixBlendMode = blendModeToCssMixBlendMode(blendMode) ?? '';
if (_canvasPool.isClipped) {
// Reset width/height since they may have been previously set.
imgElement.style..removeProperty('width')..removeProperty('height');
@@ -837,7 +836,7 @@ class BitmapCanvas extends EngineCanvas {
style
..position = 'absolute'
..backgroundImage = "url('${image.imgElement.src}')"
..backgroundBlendMode = stringForBlendMode(colorFilterBlendMode) ?? ''
..backgroundBlendMode = blendModeToCssMixBlendMode(colorFilterBlendMode) ?? ''
..backgroundColor = colorToCssString(filterColor);
break;
}
@@ -851,14 +850,11 @@ class BitmapCanvas extends EngineCanvas {
ui.BlendMode colorFilterBlendMode,
SurfacePaintData paint) {
// For srcIn blendMode, we use an svg filter to apply to image element.
final String? svgFilter =
svgFilterFromBlendMode(filterColor, colorFilterBlendMode);
final html.Element filterElement =
html.Element.html(svgFilter, treeSanitizer: NullTreeSanitizer());
rootElement.append(filterElement);
_children.add(filterElement);
final SvgFilter svgFilter = svgFilterFromBlendMode(filterColor, colorFilterBlendMode);
rootElement.append(svgFilter.element);
_children.add(svgFilter.element);
final html.HtmlElement imgElement = _reuseOrCreateImage(image);
imgElement.style.filter = 'url(#_fcf$filterIdCounter)';
imgElement.style.filter = 'url(#${svgFilter.id})';
if (colorFilterBlendMode == ui.BlendMode.saturation) {
imgElement.style.backgroundColor = colorToCssString(filterColor);
}
@@ -869,13 +865,11 @@ class BitmapCanvas extends EngineCanvas {
html.HtmlElement _createImageElementWithSvgColorMatrixFilter(
HtmlImage image, List<double> matrix, SurfacePaintData paint) {
// For srcIn blendMode, we use an svg filter to apply to image element.
final String? svgFilter = svgFilterFromColorMatrix(matrix);
final html.Element filterElement =
html.Element.html(svgFilter, treeSanitizer: NullTreeSanitizer());
rootElement.append(filterElement);
_children.add(filterElement);
final SvgFilter svgFilter = svgFilterFromColorMatrix(matrix);
rootElement.append(svgFilter.element);
_children.add(svgFilter.element);
final html.HtmlElement imgElement = _reuseOrCreateImage(image);
imgElement.style.filter = 'url(#_fcf$filterIdCounter)';
imgElement.style.filter = 'url(#${svgFilter.id})';
return imgElement;
}
@@ -1104,7 +1098,15 @@ class BitmapCanvas extends EngineCanvas {
}
}
String? stringForBlendMode(ui.BlendMode? blendMode) {
/// The CSS value for the `mix-blend-mode` CSS property.
///
/// This list includes values supposrted by SVG, but it's not the same.
///
/// See also:
///
/// * https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode
/// * [blendModeToSvgEnum], which specializes on SVG blend modes
String? blendModeToCssMixBlendMode(ui.BlendMode? blendMode) {
if (blendMode == null) {
return null;
}
@@ -1170,6 +1172,140 @@ String? stringForBlendMode(ui.BlendMode? blendMode) {
}
}
// Source: https://www.w3.org/TR/SVG11/filters.html#InterfaceSVGFEBlendElement
// These constant names deviate from Dart's camelCase convention on purpose to
// make it easier to search for them in W3 specs and in Chromium sources.
const int SVG_FEBLEND_MODE_UNKNOWN = 0;
const int SVG_FEBLEND_MODE_NORMAL = 1;
const int SVG_FEBLEND_MODE_MULTIPLY = 2;
const int SVG_FEBLEND_MODE_SCREEN = 3;
const int SVG_FEBLEND_MODE_DARKEN = 4;
const int SVG_FEBLEND_MODE_LIGHTEN = 5;
const int SVG_FEBLEND_MODE_OVERLAY = 6;
const int SVG_FEBLEND_MODE_COLOR_DODGE = 7;
const int SVG_FEBLEND_MODE_COLOR_BURN = 8;
const int SVG_FEBLEND_MODE_HARD_LIGHT = 9;
const int SVG_FEBLEND_MODE_SOFT_LIGHT = 10;
const int SVG_FEBLEND_MODE_DIFFERENCE = 11;
const int SVG_FEBLEND_MODE_EXCLUSION = 12;
const int SVG_FEBLEND_MODE_HUE = 13;
const int SVG_FEBLEND_MODE_SATURATION = 14;
const int SVG_FEBLEND_MODE_COLOR = 15;
const int SVG_FEBLEND_MODE_LUMINOSITY = 16;
// Source: https://github.com/chromium/chromium/blob/e1e495b29e1178a451f65980a6c4ae017c34dc94/third_party/blink/renderer/platform/graphics/graphics_types.cc#L55
const String kCompositeClear = 'clear';
const String kCompositeCopy = 'copy';
const String kCompositeSourceOver = 'source-over';
const String kCompositeSourceIn = 'source-in';
const String kCompositeSourceOut = 'source-out';
const String kCompositeSourceAtop = 'source-atop';
const String kCompositeDestinationOver = 'destination-over';
const String kCompositeDestinationIn = 'destination-in';
const String kCompositeDestinationOut = 'destination-out';
const String kCompositeDestinationAtop = 'destination-atop';
const String kCompositeXor = 'xor';
const String kCompositeLighter = 'lighter';
/// Compositing and blending operation in SVG.
///
/// Flutter's [BlendMode] flattens what SVG expresses as two orthogonal
/// properties, a composite operator and blend mode. Instances of this class
/// are returned from [blendModeToSvgEnum] by mapping Flutter's [BlendMode]
/// enum onto the SVG equivalent.
///
/// See also:
///
/// * https://www.w3.org/TR/compositing-1
/// * https://github.com/chromium/chromium/blob/e1e495b29e1178a451f65980a6c4ae017c34dc94/third_party/blink/renderer/platform/graphics/graphics_types.cc#L55
/// * https://github.com/chromium/chromium/blob/e1e495b29e1178a451f65980a6c4ae017c34dc94/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc#L725
class SvgBlendMode {
const SvgBlendMode(this.compositeOperator, this.blendMode);
/// The name of the SVG composite operator.
///
/// If this mode represents a blend mode, this is set to [kCompositeSourceOver].
final String compositeOperator;
/// The identifier of the SVG blend mode.
///
/// This is mode represents a compositing operation, this is set to [SVG_FEBLEND_MODE_UNKNOWN].
final int blendMode;
}
/// Converts Flutter's [ui.BlendMode] to SVG's <compositing operation, blend mode> pair.
SvgBlendMode? blendModeToSvgEnum(ui.BlendMode? blendMode) {
if (blendMode == null) {
return null;
}
switch (blendMode) {
case ui.BlendMode.clear:
return const SvgBlendMode(kCompositeClear, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.srcOver:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.srcIn:
return const SvgBlendMode(kCompositeSourceIn, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.srcOut:
return const SvgBlendMode(kCompositeSourceOut, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.srcATop:
return const SvgBlendMode(kCompositeSourceAtop, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.dstOver:
return const SvgBlendMode(kCompositeDestinationOver, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.dstIn:
return const SvgBlendMode(kCompositeDestinationIn, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.dstOut:
return const SvgBlendMode(kCompositeDestinationOut, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.dstATop:
return const SvgBlendMode(kCompositeDestinationAtop, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.plus:
return const SvgBlendMode(kCompositeLighter, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.src:
return const SvgBlendMode(kCompositeCopy, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.xor:
return const SvgBlendMode(kCompositeXor, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.multiply:
// Falling back to multiply, ignoring alpha channel.
// TODO(ferhat): only used for debug, find better fallback for web.
case ui.BlendMode.modulate:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_MULTIPLY);
case ui.BlendMode.screen:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_SCREEN);
case ui.BlendMode.overlay:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_OVERLAY);
case ui.BlendMode.darken:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_DARKEN);
case ui.BlendMode.lighten:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_LIGHTEN);
case ui.BlendMode.colorDodge:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_COLOR_DODGE);
case ui.BlendMode.colorBurn:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_COLOR_BURN);
case ui.BlendMode.hardLight:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_HARD_LIGHT);
case ui.BlendMode.softLight:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_SOFT_LIGHT);
case ui.BlendMode.difference:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_DIFFERENCE);
case ui.BlendMode.exclusion:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_EXCLUSION);
case ui.BlendMode.hue:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_HUE);
case ui.BlendMode.saturation:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_SATURATION);
case ui.BlendMode.color:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_COLOR);
case ui.BlendMode.luminosity:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_LUMINOSITY);
default:
assert(
false,
'Flutter Web does not support the blend mode: $blendMode',
);
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_NORMAL);
}
}
String? stringForStrokeCap(ui.StrokeCap? strokeCap) {
if (strokeCap == null) {
return null;
@@ -1273,10 +1409,8 @@ List<html.Element> _clipContent(List<SaveClipEntry> clipStack,
curElement.style
..transform = matrix4ToCssTransform(newClipTransform)
..transformOrigin = '0 0 0';
final String svgClipPath =
createSvgClipDef(curElement as html.HtmlElement, entry.path!);
final html.Element clipElement =
html.Element.html(svgClipPath, treeSanitizer: NullTreeSanitizer());
createSvgClipDef(curElement as html.HtmlElement, entry.path!);
clipDefs.add(clipElement);
}
}

View File

@@ -3,10 +3,10 @@
// found in the LICENSE file.
import 'dart:html' as html;
import 'dart:svg' as svg;
import 'package:ui/ui.dart' as ui;
import '../../engine.dart' show NullTreeSanitizer;
import '../dom_renderer.dart';
import '../shadow.dart';
import '../util.dart';
@@ -344,7 +344,7 @@ class PersistedPhysicalShape extends PersistedContainerSurface
/// we size the inner container to cover full pathBounds instead of sizing
/// to clipping rect bounds (which is the case for elevation == 0.0 where
/// we shift outer/inner clip area instead to position clip-path).
final String svgClipPath = elevation == 0.0
final svg.SvgSvgElement svgClipPath = elevation == 0.0
? pathToSvgClipPath(path,
offsetX: -pathBounds.left,
offsetY: -pathBounds.top,
@@ -360,8 +360,7 @@ class PersistedPhysicalShape extends PersistedContainerSurface
/// svg clip and render elements.
_clipElement?.remove();
_svgElement?.remove();
_clipElement =
html.Element.html(svgClipPath, treeSanitizer: NullTreeSanitizer());
_clipElement = svgClipPath;
domRenderer.append(rootElement!, _clipElement!);
if (elevation == 0.0) {
DomRenderer.setClipPath(rootElement!, createSvgClipUrl());
@@ -486,10 +485,7 @@ class PersistedClipPath extends PersistedContainerSurface
@override
void apply() {
_clipElement?.remove();
final String svgClipPath =
createSvgClipDef(childContainer! as html.HtmlElement, clipPath);
_clipElement =
html.Element.html(svgClipPath, treeSanitizer: NullTreeSanitizer());
_clipElement = createSvgClipDef(childContainer! as html.HtmlElement, clipPath);
domRenderer.append(childContainer!, _clipElement!);
}
@@ -518,9 +514,9 @@ class PersistedClipPath extends PersistedContainerSurface
}
/// Creates an svg clipPath and applies it to [element].
String createSvgClipDef(html.HtmlElement element, ui.Path clipPath) {
svg.SvgSvgElement createSvgClipDef(html.HtmlElement element, ui.Path clipPath) {
final ui.Rect pathBounds = clipPath.getBounds();
final String svgClipPath = pathToSvgClipPath(clipPath,
final svg.SvgSvgElement svgClipPath = pathToSvgClipPath(clipPath,
scaleX: 1.0 / pathBounds.right, scaleY: 1.0 / pathBounds.bottom);
DomRenderer.setClipPath(element, createSvgClipUrl());
// We need to set width and height for the clipElement to cover the

View File

@@ -3,10 +3,11 @@
// found in the LICENSE file.
import 'dart:html' as html;
import 'dart:svg' as svg;
import 'package:ui/ui.dart' as ui;
import '../../engine.dart' show NullTreeSanitizer;
import '../browser_detection.dart';
import '../canvaskit/color_filter.dart';
import '../color_filter.dart';
import '../dom_renderer.dart';
@@ -135,30 +136,22 @@ class PersistedColorFilter extends PersistedContainerSurface
}
// Use SVG filter for blend mode.
final String? svgFilter =
svgFilterFromBlendMode(filterColor, colorFilterBlendMode);
if (svgFilter != null) {
_filterElement =
html.Element.html(svgFilter, treeSanitizer: NullTreeSanitizer());
//rootElement!.insertBefore(_filterElement!, childContainer!);
domRenderer.addResource(_filterElement!);
style.filter = 'url(#_fcf$filterIdCounter)';
if (colorFilterBlendMode == ui.BlendMode.saturation ||
colorFilterBlendMode == ui.BlendMode.multiply ||
colorFilterBlendMode == ui.BlendMode.modulate) {
style.backgroundColor = colorToCssString(filterColor);
}
final SvgFilter svgFilter = svgFilterFromBlendMode(filterColor, colorFilterBlendMode);
_filterElement = svgFilter.element;
domRenderer.addResource(_filterElement!);
style.filter = 'url(#${svgFilter.id})';
if (colorFilterBlendMode == ui.BlendMode.saturation ||
colorFilterBlendMode == ui.BlendMode.multiply ||
colorFilterBlendMode == ui.BlendMode.modulate) {
style.backgroundColor = colorToCssString(filterColor);
}
}
void _applyMatrixColorFilter(CkMatrixColorFilter colorFilter) {
final String? svgFilter = svgFilterFromColorMatrix(colorFilter.matrix);
if (svgFilter != null) {
_filterElement =
html.Element.html(svgFilter, treeSanitizer: NullTreeSanitizer());
domRenderer.addResource(_filterElement!);
childContainer!.style.filter = 'url(#_fcf$filterIdCounter)';
}
final SvgFilter svgFilter = svgFilterFromColorMatrix(colorFilter.matrix);
_filterElement = svgFilter.element;
domRenderer.addResource(_filterElement!);
childContainer!.style.filter = 'url(#${svgFilter.id})';
}
@override
@@ -171,9 +164,9 @@ class PersistedColorFilter extends PersistedContainerSurface
}
}
String? svgFilterFromBlendMode(
SvgFilter svgFilterFromBlendMode(
ui.Color? filterColor, ui.BlendMode colorFilterBlendMode) {
String? svgFilter;
final SvgFilter svgFilter;
switch (colorFilterBlendMode) {
case ui.BlendMode.srcIn:
case ui.BlendMode.srcATop:
@@ -199,8 +192,11 @@ String? svgFilterFromBlendMode(
case ui.BlendMode.overlay:
// Since overlay is the same as hard-light by swapping layers,
// pass hard-light blend function.
svgFilter =
_blendColorFilterToSvg(filterColor, 'hard-light', swapLayers: true);
svgFilter = _blendColorFilterToSvg(
filterColor,
blendModeToSvgEnum(ui.BlendMode.hardLight)!,
swapLayers: true,
);
break;
// Several of the filters below (although supported) do not render the
// same (close but not exact) as native flutter when used as blend mode
@@ -228,7 +224,7 @@ String? svgFilterFromBlendMode(
case ui.BlendMode.difference:
case ui.BlendMode.exclusion:
svgFilter = _blendColorFilterToSvg(
filterColor, stringForBlendMode(colorFilterBlendMode)!);
filterColor, blendModeToSvgEnum(colorFilterBlendMode)!);
break;
case ui.BlendMode.src:
case ui.BlendMode.dst:
@@ -237,33 +233,155 @@ String? svgFilterFromBlendMode(
case ui.BlendMode.dstOver:
case ui.BlendMode.clear:
case ui.BlendMode.srcOver:
assert(
false,
'Invalid svg filter request for blend-mode '
'$colorFilterBlendMode');
break;
throw UnimplementedError(
'Blend mode not supported in HTML renderer: $colorFilterBlendMode',
);
}
return svgFilter;
}
String? svgFilterFromColorMatrix(List<double> matrix) {
filterIdCounter += 1;
final StringBuffer sbMatrix = StringBuffer();
assert(matrix.length == 20);
for (int i = 0; i < 20; i++) {
if (i != 0) {
sbMatrix.write(' ');
}
sbMatrix.write(matrix[i]);
// See: https://www.w3.org/TR/SVG11/types.html#InterfaceSVGUnitTypes
const int kObjectBoundingBox = 2;
// See: https://www.w3.org/TR/SVG11/filters.html#InterfaceSVGFEColorMatrixElement
const int kMatrixType = 1;
// See: https://www.w3.org/TR/SVG11/filters.html#InterfaceSVGFECompositeElement
const int kOperatorOut = 3;
const int kOperatorAtop = 4;
const int kOperatorXor = 5;
const int kOperatorArithmetic = 6;
/// Builds an [SvgFilter].
class SvgFilterBuilder {
static int _filterIdCounter = 0;
SvgFilterBuilder() : id = '_fcf${++_filterIdCounter}' {
filter.id = id;
// SVG filters that contain `<feImage>` will fail on several browsers
// (e.g. Firefox) if bounds are not specified.
filter.filterUnits!.baseVal = kObjectBoundingBox;
// On Firefox percentage width/height 100% works however fails in Chrome 88.
filter.x!.baseVal!.valueAsString = '0%';
filter.y!.baseVal!.valueAsString = '0%';
filter.width!.baseVal!.valueAsString = '100%';
filter.height!.baseVal!.valueAsString = '100%';
}
final String id;
final svg.SvgSvgElement root = kSvgResourceHeader.clone(false) as svg.SvgSvgElement;
final svg.FilterElement filter = svg.FilterElement();
set colorInterpolationFilters(String filters) {
filter.setAttribute('color-interpolation-filters', filters);
}
void setFeColorMatrix(List<double> matrix, { required String result }) {
final svg.FEColorMatrixElement element = svg.FEColorMatrixElement();
element.type!.baseVal = kMatrixType;
element.result!.baseVal = result;
final svg.NumberList value = element.values!.baseVal!;
for (int i = 0; i < matrix.length; i++) {
value.appendItem(root.createSvgNumber()..value = matrix[i]);
}
filter.append(element);
}
void setFeFlood({
required String floodColor,
required String floodOpacity,
required String result,
}) {
final svg.FEFloodElement element = svg.FEFloodElement();
element.setAttribute('flood-color', floodColor);
element.setAttribute('flood-opacity', floodOpacity);
element.result!.baseVal = result;
filter.append(element);
}
void setFeBlend({
required String in1,
required String in2,
required int mode,
}) {
final svg.FEBlendElement element = svg.FEBlendElement();
element.in1!.baseVal = in1;
element.in2!.baseVal = in2;
element.mode!.baseVal = mode;
filter.append(element);
}
void setFeComposite({
required String in1,
required String in2,
required int operator,
num? k1,
num? k2,
num? k3,
num? k4,
required String result,
}) {
final svg.FECompositeElement element = svg.SvgElement.tag('feComposite') as svg.FECompositeElement;
element.in1!.baseVal = in1;
element.in2!.baseVal = in2;
element.operator!.baseVal = operator;
if (k1 != null) {
element.k1!.baseVal = k1;
}
if (k2 != null) {
element.k2!.baseVal = k2;
}
if (k3 != null) {
element.k3!.baseVal = k3;
}
if (k4 != null) {
element.k4!.baseVal = k4;
}
element.result!.baseVal = result;
filter.append(element);
}
void setFeImage({
required String href,
required String result,
required double width,
required double height,
}) {
final svg.FEImageElement element = svg.FEImageElement();
element.href!.baseVal = href;
element.result!.baseVal = result;
// WebKit will not render if x/y/width/height is specified. So we return
// explicit size here unless running on WebKit.
if (browserEngine != BrowserEngine.webkit) {
element.x!.baseVal!.newValueSpecifiedUnits(svg.Length.SVG_LENGTHTYPE_NUMBER, 0);
element.y!.baseVal!.newValueSpecifiedUnits(svg.Length.SVG_LENGTHTYPE_NUMBER, 0);
element.width!.baseVal!.newValueSpecifiedUnits(svg.Length.SVG_LENGTHTYPE_NUMBER, width);
element.height!.baseVal!.newValueSpecifiedUnits(svg.Length.SVG_LENGTHTYPE_NUMBER, height);
}
filter.append(element);
}
SvgFilter build() {
root.append(filter);
return SvgFilter._(id, root);
}
return '$kSvgResourceHeader'
'<filter id="_fcf$filterIdCounter" '
'filterUnits="objectBoundingBox" x="0%" y="0%" width="100%" height="100%">'
'<feColorMatrix type="matrix" values="$sbMatrix" result="comp"/>'
'</filter></svg>';
}
int filterIdCounter = 0;
class SvgFilter {
SvgFilter._(this.id, this.element);
final String id;
final svg.SvgSvgElement element;
}
SvgFilter svgFilterFromColorMatrix(List<double> matrix) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeColorMatrix(matrix, result: 'comp');
return builder.build();
}
// The color matrix for feColorMatrix element changes colors based on
// the following:
@@ -278,109 +396,161 @@ int filterIdCounter = 0;
// G' = g1*R + g2*G + g3*B + g4*A + g5
// B' = b1*R + b2*G + b3*B + b4*A + b5
// A' = a1*R + a2*G + a3*B + a4*A + a5
String _srcInColorFilterToSvg(ui.Color? color) {
filterIdCounter += 1;
return '$kSvgResourceHeader'
'<filter id="_fcf$filterIdCounter" color-interpolation-filters="sRGB" '
'filterUnits="objectBoundingBox" x="0%" y="0%" width="100%" height="100%">'
'<feColorMatrix type="matrix" values="0 0 0 0 1\n' // Ignore input, set it to absolute.
'0 0 0 0 1\n'
'0 0 0 0 1\n'
'0 0 0 1 0" result="destalpha"></feColorMatrix>>' // Just take alpha channel of destination
'<feFlood flood-color="${colorToCssString(color)}" flood-opacity="1" result="flood">'
'</feFlood>'
'<feComposite in="flood" in2="destalpha" '
'operator="arithmetic" k1="1" k2="0" k3="0" k4="0" result="comp">'
'</feComposite>'
'</filter></svg>';
SvgFilter _srcInColorFilterToSvg(ui.Color? color) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.colorInterpolationFilters = 'sRGB';
builder.setFeColorMatrix(
const <double>[
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
0, 0, 0, 1, 0,
],
result: 'destalpha',
);
builder.setFeFlood(
floodColor: colorToCssString(color) ?? '',
floodOpacity: '1',
result: 'flood',
);
builder.setFeComposite(
in1: 'flood',
in2: 'destalpha',
operator: kOperatorArithmetic,
k1: 1,
k2: 0,
k3: 0,
k4: 0,
result: 'comp',
);
return builder.build();
}
/// The destination that overlaps the source is composited with the source and
/// replaces the destination. dst-atop CR = CB*αB*αA+CA*αA*(1-αB) αR=αA
String _dstATopColorFilterToSvg(ui.Color? color) {
filterIdCounter += 1;
return '$kSvgResourceHeader'
'<filter id="_fcf$filterIdCounter" '
'filterUnits="objectBoundingBox" x="0%" y="0%" width="100%" height="100%">'
'<feFlood flood-color="${colorToCssString(color)}" flood-opacity="1" result="flood">'
'</feFlood>'
'<feComposite in="SourceGraphic" in2="flood" operator="atop" result="comp">'
'</feComposite>'
'</filter></svg>';
SvgFilter _dstATopColorFilterToSvg(ui.Color? color) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(
floodColor: colorToCssString(color) ?? '',
floodOpacity: '1',
result: 'flood',
);
builder.setFeComposite(
in1: 'SourceGraphic',
in2: 'flood',
operator: kOperatorAtop,
result: 'comp',
);
return builder.build();
}
String _srcOutColorFilterToSvg(ui.Color? color) {
filterIdCounter += 1;
return '$kSvgResourceHeader'
'<filter id="_fcf$filterIdCounter" '
'filterUnits="objectBoundingBox" x="0%" y="0%" width="100%" height="100%">'
'<feFlood flood-color="${colorToCssString(color)}" flood-opacity="1" result="flood">'
'</feFlood>'
'<feComposite in="flood" in2="SourceGraphic" operator="out" result="comp">'
'</feComposite>'
'</filter></svg>';
SvgFilter _srcOutColorFilterToSvg(ui.Color? color) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(
floodColor: colorToCssString(color) ?? '',
floodOpacity: '1',
result: 'flood',
);
builder.setFeComposite(
in1: 'flood',
in2: 'SourceGraphic',
operator: kOperatorOut,
result: 'comp',
);
return builder.build();
}
String _xorColorFilterToSvg(ui.Color? color) {
filterIdCounter += 1;
return '$kSvgResourceHeader'
'<filter id="_fcf$filterIdCounter" '
'filterUnits="objectBoundingBox" x="0%" y="0%" width="100%" height="100%">'
'<feFlood flood-color="${colorToCssString(color)}" flood-opacity="1" result="flood">'
'</feFlood>'
'<feComposite in="flood" in2="SourceGraphic" operator="xor" result="comp">'
'</feComposite>'
'</filter></svg>';
SvgFilter _xorColorFilterToSvg(ui.Color? color) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(
floodColor: colorToCssString(color) ?? '',
floodOpacity: '1',
result: 'flood',
);
builder.setFeComposite(
in1: 'flood',
in2: 'SourceGraphic',
operator: kOperatorXor,
result: 'comp',
);
return builder.build();
}
// The source image and color are composited using :
// result = k1 *in*in2 + k2*in + k3*in2 + k4.
String _compositeColorFilterToSvg(
SvgFilter _compositeColorFilterToSvg(
ui.Color? color, double k1, double k2, double k3, double k4) {
filterIdCounter += 1;
return '$kSvgResourceHeader'
'<filter id="_fcf$filterIdCounter" '
'filterUnits="objectBoundingBox" x="0%" y="0%" width="100%" height="100%">'
'<feFlood flood-color="${colorToCssString(color)}" flood-opacity="1" result="flood">'
'</feFlood>'
'<feComposite in="flood" in2="SourceGraphic" '
'operator="arithmetic" k1="$k1" k2="$k2" k3="$k3" k4="$k4" result="comp">'
'</feComposite>'
'</filter></svg>';
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(
floodColor: colorToCssString(color) ?? '',
floodOpacity: '1',
result: 'flood',
);
builder.setFeComposite(
in1: 'flood',
in2: 'SourceGraphic',
operator: kOperatorArithmetic,
k1: k1,
k2: k2,
k3: k3,
k4: k4,
result: 'comp',
);
return builder.build();
}
// Porter duff source * destination , keep source alpha.
// First apply color filter to source to change it to [color], then
// composite using multiplication.
String _modulateColorFilterToSvg(ui.Color color) {
filterIdCounter += 1;
SvgFilter _modulateColorFilterToSvg(ui.Color color) {
final double r = color.red / 255.0;
final double b = color.blue / 255.0;
final double g = color.green / 255.0;
return '$kSvgResourceHeader'
'<filter id="_fcf$filterIdCounter" '
'filterUnits="objectBoundingBox" x="0%" y="0%" width="100%" height="100%">'
'<feColorMatrix values="0 0 0 0 $r ' // Ignore input, set it to absolute.
'0 0 0 0 $g '
'0 0 0 0 $b '
'0 0 0 1 0" result="recolor"/>'
'<feComposite in="recolor" in2="SourceGraphic" '
'operator="arithmetic" k1="1" k2="0" k3="0" k4="0" result="comp">'
'</feComposite>'
'</filter></svg>';
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeColorMatrix(
<double>[
0, 0, 0, 0, r,
0, 0, 0, 0, g,
0, 0, 0, 0, b,
0, 0, 0, 1, 0,
],
result: 'recolor',
);
builder.setFeComposite(
in1: 'recolor',
in2: 'SourceGraphic',
operator: kOperatorArithmetic,
k1: 1,
k2: 0,
k3: 0,
k4: 0,
result: 'comp',
);
return builder.build();
}
// Uses feBlend element to blend source image with a color.
String _blendColorFilterToSvg(ui.Color? color, String feBlend,
SvgFilter _blendColorFilterToSvg(ui.Color? color, SvgBlendMode svgBlendMode,
{bool swapLayers = false}) {
filterIdCounter += 1;
return '$kSvgResourceHeader'
'<filter id="_fcf$filterIdCounter" filterUnits="objectBoundingBox" '
'x="0%" y="0%" width="100%" height="100%">'
'<feFlood flood-color="${colorToCssString(color)}" flood-opacity="1" result="flood">'
'</feFlood>' +
(swapLayers
? '<feBlend in="SourceGraphic" in2="flood" mode="$feBlend"/>'
: '<feBlend in="flood" in2="SourceGraphic" mode="$feBlend"/>') +
'</filter></svg>';
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(
floodColor: colorToCssString(color) ?? '',
floodOpacity: '1',
result: 'flood',
);
if (swapLayers) {
builder.setFeBlend(
in1: 'SourceGraphic',
in2: 'flood',
mode: svgBlendMode.blendMode,
);
} else {
builder.setFeBlend(
in1: 'flood',
in2: 'SourceGraphic',
mode: svgBlendMode.blendMode,
);
}
return builder.build();
}

View File

@@ -4,11 +4,11 @@
import 'dart:html' as html;
import 'dart:math' as math;
import 'dart:svg' as svg;
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../../engine.dart' show NullTreeSanitizer;
import '../browser_detection.dart';
import '../dom_renderer.dart';
import '../engine_canvas.dart';
@@ -273,31 +273,33 @@ String _borderStrokeToCssUnit(double value) {
return '${value.toStringAsFixed(3)}px';
}
html.Element pathToSvgElement(
svg.SvgSvgElement pathToSvgElement(
SurfacePath path, SurfacePaintData paint, String width, String height) {
final StringBuffer sb = StringBuffer();
sb.write(
'<svg viewBox="0 0 $width $height" width="${width}px" height="${height}px">');
sb.write('<path ');
// In Firefox some SVG typed attributes are returned as null without a
// setter. So we use strings here.
final svg.SvgSvgElement root = svg.SvgSvgElement()
..setAttribute('width', '${width}px')
..setAttribute('height', '${height}px')
..setAttribute('viewBox', '0 0 $width $height');
final svg.PathElement svgPath = svg.PathElement();
root.append(svgPath);
final ui.Color color = paint.color ?? const ui.Color(0xFF000000);
if (paint.style == ui.PaintingStyle.stroke ||
(paint.style != ui.PaintingStyle.fill &&
paint.strokeWidth != 0 &&
paint.strokeWidth != null)) {
sb.write('stroke="${colorToCssString(color)}" ');
sb.write('stroke-width="${paint.strokeWidth ?? 1.0}" ');
sb.write('fill="none" ');
svgPath.setAttribute('stroke', colorToCssString(color)!);
svgPath.setAttribute('stroke-width', '${paint.strokeWidth ?? 1.0}');
svgPath.setAttribute('fill', 'none');
} else if (paint.color != null) {
sb.write('fill="${colorToCssString(color)}" ');
svgPath.setAttribute('fill', colorToCssString(color)!);
} else {
sb.write('fill="#000000" ');
svgPath.setAttribute('fill', '#000000');
}
if (path.fillType == ui.PathFillType.evenOdd) {
sb.write('fill-rule="evenodd" ');
svgPath.setAttribute('fill-rule', 'evenodd');
}
sb.write('d="');
pathToSvg(path.pathRef, sb);
sb.write('"></path>');
sb.write('</svg>');
return html.Element.html(sb.toString(), treeSanitizer: NullTreeSanitizer());
svgPath.setAttribute('d', pathToSvg(path.pathRef));
return root;
}

View File

@@ -12,25 +12,25 @@ import 'path_utils.dart';
/// Converts [path] to SVG path syntax to be used as "d" attribute in path
/// element.
void pathToSvg(PathRef pathRef, StringBuffer sb,
{double offsetX = 0, double offsetY = 0}) {
String pathToSvg(PathRef pathRef, {double offsetX = 0, double offsetY = 0}) {
final StringBuffer buffer = StringBuffer();
final PathRefIterator iter = PathRefIterator(pathRef);
int verb = 0;
final Float32List outPts = Float32List(PathRefIterator.kMaxBufferSize);
while ((verb = iter.next(outPts)) != SPath.kDoneVerb) {
switch (verb) {
case SPath.kMoveVerb:
sb.write('M ${outPts[0] + offsetX} ${outPts[1] + offsetY}');
buffer.write('M ${outPts[0] + offsetX} ${outPts[1] + offsetY}');
break;
case SPath.kLineVerb:
sb.write('L ${outPts[2] + offsetX} ${outPts[3] + offsetY}');
buffer.write('L ${outPts[2] + offsetX} ${outPts[3] + offsetY}');
break;
case SPath.kCubicVerb:
sb.write('C ${outPts[2] + offsetX} ${outPts[3] + offsetY} '
buffer.write('C ${outPts[2] + offsetX} ${outPts[3] + offsetY} '
'${outPts[4] + offsetX} ${outPts[5] + offsetY} ${outPts[6] + offsetX} ${outPts[7] + offsetY}');
break;
case SPath.kQuadVerb:
sb.write('Q ${outPts[2] + offsetX} ${outPts[3] + offsetY} '
buffer.write('Q ${outPts[2] + offsetX} ${outPts[3] + offsetY} '
'${outPts[4] + offsetX} ${outPts[5] + offsetY}');
break;
case SPath.kConicVerb:
@@ -44,15 +44,16 @@ void pathToSvg(PathRef pathRef, StringBuffer sb,
final double p1y = points[i].dy;
final double p2x = points[i + 1].dx;
final double p2y = points[i + 1].dy;
sb.write('Q ${p1x + offsetX} ${p1y + offsetY} '
buffer.write('Q ${p1x + offsetX} ${p1y + offsetY} '
'${p2x + offsetX} ${p2y + offsetY}');
}
break;
case SPath.kCloseVerb:
sb.write('Z');
buffer.write('Z');
break;
default:
throw UnimplementedError('Unknown path verb $verb');
}
}
return buffer.toString();
}

View File

@@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:svg' as svg;
import 'package:ui/ui.dart' as ui;
import '../browser_detection.dart';
@@ -15,38 +17,43 @@ int _clipIdCounter = 0;
///
/// Position needs to be absolute since these svgs are sandwiched between
/// canvas elements and can cause layout shifts otherwise.
const String kSvgResourceHeader = '<svg width="0" height="0" '
'style="position:absolute">';
final svg.SvgSvgElement kSvgResourceHeader = svg.SvgSvgElement()
..setAttribute('width', 0)
..setAttribute('height', 0)
..style.position = 'absolute';
/// Converts Path to svg element that contains a clip-path definition.
///
/// Calling this method updates [_clipIdCounter]. The HTML id of the generated
/// clip is set to "svgClip${_clipIdCounter}", e.g. "svgClip123".
String pathToSvgClipPath(ui.Path path,
svg.SvgSvgElement pathToSvgClipPath(ui.Path path,
{double offsetX = 0,
double offsetY = 0,
double scaleX = 1.0,
double scaleY = 1.0}) {
_clipIdCounter += 1;
final StringBuffer sb = StringBuffer();
sb.write(kSvgResourceHeader);
sb.write('<defs>');
final svg.SvgSvgElement root = kSvgResourceHeader.clone(false) as svg.SvgSvgElement;
final svg.DefsElement defs = svg.DefsElement();
root.append(defs);
final String clipId = 'svgClip$_clipIdCounter';
final svg.ClipPathElement clipPath = svg.ClipPathElement();
defs.append(clipPath);
clipPath.id = clipId;
if (browserEngine == BrowserEngine.firefox) {
// Firefox objectBoundingBox fails to scale to 1x1 units, instead use
// no clipPathUnits but write the path in target units.
sb.write('<clipPath id=$clipId>');
sb.write('<path fill="#FFFFFF" d="');
} else {
sb.write('<clipPath id=$clipId clipPathUnits="objectBoundingBox">');
sb.write('<path transform="scale($scaleX, $scaleY)" fill="#FFFFFF" d="');
final svg.PathElement svgPath = svg.PathElement();
clipPath.append(svgPath);
svgPath.setAttribute('fill', '#FFFFFF');
// Firefox objectBoundingBox fails to scale to 1x1 units, instead use
// no clipPathUnits but write the path in target units.
if (browserEngine != BrowserEngine.firefox) {
clipPath.setAttribute('clipPathUnits', 'objectBoundingBox');
svgPath.setAttribute('transform', 'scale($scaleX, $scaleY)');
}
pathToSvg((path as SurfacePath).pathRef, sb, offsetX: offsetX, offsetY: offsetY);
sb.write('"></path></clipPath></defs></svg');
return sb.toString();
svgPath.setAttribute('d', pathToSvg((path as SurfacePath).pathRef, offsetX: offsetX, offsetY: offsetY));
return root;
}
String createSvgClipUrl() => 'url(#svgClip$_clipIdCounter)';

View File

@@ -6,11 +6,10 @@ import 'dart:html' as html;
import 'package:ui/ui.dart' as ui;
import '../../engine.dart' show NullTreeSanitizer;
import '../browser_detection.dart';
import '../dom_renderer.dart';
import 'bitmap_canvas.dart';
import 'path_to_svg_clip.dart';
import 'color_filter.dart';
import 'shaders/shader.dart';
import 'surface.dart';
@@ -155,15 +154,13 @@ class PersistedShaderMask extends PersistedContainerSurface
break;
}
final String code = svgMaskFilterFromImageAndBlendMode(
imageUrl, blendModeTemp, maskRect.width, maskRect.height)!;
_shaderElement =
html.Element.html(code, treeSanitizer: NullTreeSanitizer());
final SvgFilter svgFilter = svgMaskFilterFromImageAndBlendMode(
imageUrl, blendModeTemp, maskRect.width, maskRect.height);
_shaderElement = svgFilter.element;
if (isWebKit) {
_childContainer!.style.filter = 'url(#_fmf$_maskFilterIdCounter';
_childContainer!.style.filter = 'url(#${svgFilter.id})';
} else {
rootElement!.style.filter = 'url(#_fmf$_maskFilterIdCounter';
rootElement!.style.filter = 'url(#${svgFilter.id})';
}
domRenderer.addResource(_shaderElement!);
}
@@ -180,9 +177,9 @@ class PersistedShaderMask extends PersistedContainerSurface
}
}
String? svgMaskFilterFromImageAndBlendMode(
SvgFilter svgMaskFilterFromImageAndBlendMode(
String imageUrl, ui.BlendMode blendMode, double width, double height) {
String? svgFilter;
final SvgFilter svgFilter;
switch (blendMode) {
case ui.BlendMode.src:
svgFilter = _srcImageToSvg(imageUrl, width, height);
@@ -208,8 +205,13 @@ String? svgMaskFilterFromImageAndBlendMode(
case ui.BlendMode.overlay:
// Since overlay is the same as hard-light by swapping layers,
// pass hard-light blend function.
svgFilter = _blendImageToSvg(imageUrl, 'hard-light', width, height,
swapLayers: true);
svgFilter = _blendImageToSvg(
imageUrl,
blendModeToSvgEnum(ui.BlendMode.hardLight)!,
width,
height,
swapLayers: true,
);
break;
// Several of the filters below (although supported) do not render the
// same (close but not exact) as native flutter when used as blend mode
@@ -237,7 +239,7 @@ String? svgMaskFilterFromImageAndBlendMode(
case ui.BlendMode.difference:
case ui.BlendMode.exclusion:
svgFilter = _blendImageToSvg(
imageUrl, stringForBlendMode(blendMode), width, height);
imageUrl, blendModeToSvgEnum(blendMode)!, width, height);
break;
case ui.BlendMode.dst:
case ui.BlendMode.dstATop:
@@ -252,26 +254,6 @@ String? svgMaskFilterFromImageAndBlendMode(
return svgFilter;
}
int _maskFilterIdCounter = 0;
String _svgFilterWrapper(String content) {
_maskFilterIdCounter++;
return '$kSvgResourceHeader<filter id="_fmf$_maskFilterIdCounter" '
'filterUnits="objectBoundingBox">' +
content +
'</filter></svg>';
}
/// SVG filters that contain feImage, will fail on several browsers
/// (Firefox etc) if bounds are not specified. On Firefox percentage
/// width/height 100% works however fails in Chrome 88. Webkit will
/// not render if x/y/width/height is specified. So we return explicit size
/// here unless running on webkit.
String _buildFeBlend(double width, double height) =>
browserEngine == BrowserEngine.webkit
? ''
: 'x="0" y="0" width="${width}px" height="${height}px"';
// The color matrix for feColorMatrix element changes colors based on
// the following:
//
@@ -285,78 +267,152 @@ String _buildFeBlend(double width, double height) =>
// G' = g1*R + g2*G + g3*B + g4*A + g5
// B' = b1*R + b2*G + b3*B + b4*A + b5
// A' = a1*R + a2*G + a3*B + a4*A + a5
String _srcInImageToSvg(String imageUrl, double width, double height) {
return _svgFilterWrapper(
'<feColorMatrix values="0 0 0 0 1 ' // Ignore input, set it to absolute.
'0 0 0 0 1 '
'0 0 0 0 1 '
'0 0 0 1 0" result="destalpha"/>' // Just take alpha channel of destination
'<feImage href="$imageUrl" result="image"'
' ${_buildFeBlend(width, height)}>'
'</feImage>'
'<feComposite in="image" in2="destalpha" '
'operator="arithmetic" k1="1" k2="0" k3="0" k4="0" result="comp">'
'</feComposite>',
SvgFilter _srcInImageToSvg(String imageUrl, double width, double height) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeColorMatrix(
const <double>[
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
0, 0, 0, 1, 0,
],
result: 'destalpha',
);
builder.setFeImage(
href: imageUrl,
result: 'image',
width: width,
height: height,
);
builder.setFeComposite(
in1: 'image',
in2: 'destalpha',
operator: kOperatorArithmetic,
k1: 1,
k2: 0,
k3: 0,
k4: 0,
result: 'comp',
);
return builder.build();
}
String _srcImageToSvg(String imageUrl, double width, double height) {
return _svgFilterWrapper('<feImage href="$imageUrl" result="comp"'
' ${_buildFeBlend(width, height)}>'
'</feImage>');
SvgFilter _srcImageToSvg(String imageUrl, double width, double height) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeImage(
href: imageUrl,
result: 'comp',
width: width,
height: height,
);
return builder.build();
}
String _srcOutImageToSvg(String imageUrl, double width, double height) {
return _svgFilterWrapper('<feImage href="$imageUrl" result="image"'
' ${_buildFeBlend(width, height)}>'
'</feImage>'
'<feComposite in="image" in2="SourceGraphic" operator="out" result="comp">'
'</feComposite>');
SvgFilter _srcOutImageToSvg(String imageUrl, double width, double height) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeImage(
href: imageUrl,
result: 'image',
width: width,
height: height,
);
builder.setFeComposite(
in1: 'image',
in2: 'SourceGraphic',
operator: kOperatorOut,
result: 'comp',
);
return builder.build();
}
String _xorImageToSvg(String imageUrl, double width, double height) {
return _svgFilterWrapper('<feImage href="$imageUrl" result="image"'
' ${_buildFeBlend(width, height)}>'
'</feImage>'
'<feComposite in="image" in2="SourceGraphic" operator="xor" result="comp">'
'</feComposite>');
SvgFilter _xorImageToSvg(String imageUrl, double width, double height) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeImage(
href: imageUrl,
result: 'image',
width: width,
height: height,
);
builder.setFeComposite(
in1: 'image',
in2: 'SourceGraphic',
operator: kOperatorXor,
result: 'comp',
);
return builder.build();
}
// The source image and color are composited using :
// result = k1 *in*in2 + k2*in + k3*in2 + k4.
String _compositeImageToSvg(String imageUrl, double k1, double k2, double k3,
SvgFilter _compositeImageToSvg(String imageUrl, double k1, double k2, double k3,
double k4, double width, double height) {
return _svgFilterWrapper(
'<feImage href="$imageUrl" result="image" ${_buildFeBlend(width, height)}>'
'</feImage>'
'<feComposite in="image" in2="SourceGraphic" '
'operator="arithmetic" k1="$k1" k2="$k2" k3="$k3" k4="$k4" result="comp">'
'</feComposite>',
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeImage(
href: imageUrl,
result: 'image',
width: width,
height: height,
);
builder.setFeComposite(
in1: 'image',
in2: 'SourceGraphic',
operator: kOperatorArithmetic,
k1: k1,
k2: k2,
k3: k3,
k4: k4,
result: 'comp',
);
return builder.build();
}
// Porter duff source * destination , keep source alpha.
// First apply color filter to source to change it to [color], then
// composite using multiplication.
String _modulateImageToSvg(String imageUrl, double width, double height) {
return _svgFilterWrapper(
'<feImage href="$imageUrl" result="image" ${_buildFeBlend(width, height)}>'
'</feImage>'
'<feComposite in="image" in2="SourceGraphic" '
'operator="arithmetic" k1="1" k2="0" k3="0" k4="0" result="comp">'
'</feComposite>',
SvgFilter _modulateImageToSvg(String imageUrl, double width, double height) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeImage(
href: imageUrl,
result: 'image',
width: width,
height: height,
);
builder.setFeComposite(
in1: 'image',
in2: 'SourceGraphic',
operator: kOperatorArithmetic,
k1: 1,
k2: 0,
k3: 0,
k4: 0,
result: 'comp',
);
return builder.build();
}
// Uses feBlend element to blend source image with a color.
String _blendImageToSvg(
String imageUrl, String? feBlend, double width, double height,
SvgFilter _blendImageToSvg(
String imageUrl, SvgBlendMode svgBlendMode, double width, double height,
{bool swapLayers = false}) {
return _svgFilterWrapper(
'<feImage href="$imageUrl" result="image" ${_buildFeBlend(width, height)}>'
'</feImage>' +
(swapLayers
? '<feBlend in="SourceGraphic" in2="image" mode="$feBlend"/>'
: '<feBlend in="image" in2="SourceGraphic" mode="$feBlend"/>'),
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeImage(
href: imageUrl,
result: 'image',
width: width,
height: height,
);
if (swapLayers) {
builder.setFeBlend(
in1: 'SourceGraphic',
in2: 'image',
mode: svgBlendMode.blendMode,
);
} else {
builder.setFeBlend(
in1: 'image',
in2: 'SourceGraphic',
mode: svgBlendMode.blendMode,
);
}
return builder.build();
}

View File

@@ -3,6 +3,7 @@
// found in the LICENSE file.
import 'dart:html' as html;
import 'dart:svg' as svg;
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
@@ -186,29 +187,27 @@ Future<void> testMain() async {
html.Element pathToSvgElement(Path path, Paint paint, bool enableFill) {
final Rect bounds = path.getBounds();
final StringBuffer sb = StringBuffer();
sb.write('<svg viewBox="0 0 ${bounds.right} ${bounds.bottom}" '
'width="${bounds.right}" height="${bounds.bottom}">');
sb.write('<path ');
final svg.SvgSvgElement root = svg.SvgSvgElement();
root.style.transform = 'translate(200px, 0px)';
root.setAttribute('viewBox', '0 0 ${bounds.right} ${bounds.bottom}');
root.width!.baseVal!.newValueSpecifiedUnits(svg.Length.SVG_LENGTHTYPE_NUMBER, bounds.right);
root.height!.baseVal!.newValueSpecifiedUnits(svg.Length.SVG_LENGTHTYPE_NUMBER, bounds.bottom);
final svg.PathElement pathElement = svg.PathElement();
root.append(pathElement);
if (paint.style == PaintingStyle.stroke ||
paint.strokeWidth != 0.0) {
sb.write('stroke="${colorToCssString(paint.color)}" ');
sb.write('stroke-width="${paint.strokeWidth}" ');
pathElement.setAttribute('stroke', colorToCssString(paint.color)!);
pathElement.setAttribute('stroke-width', paint.strokeWidth);
if (!enableFill) {
sb.write('fill="none" ');
pathElement.setAttribute('fill', 'none');
}
}
if (paint.style == PaintingStyle.fill) {
sb.write('fill="${colorToCssString(paint.color)}" ');
pathElement.setAttribute('fill', colorToCssString(paint.color)!);
}
sb.write('d="');
pathToSvg((path as SurfacePath).pathRef, sb); // This is what we're testing!
sb.write('"></path>');
sb.write('</svg>');
final html.Element svgElement =
html.Element.html(sb.toString(), treeSanitizer: NullTreeSanitizer());
svgElement.style.transform = 'translate(200px, 0px)';
return svgElement;
pathElement.setAttribute('d', pathToSvg((path as SurfacePath).pathRef)); // This is what we're testing!
return root;
}
class ArcSample {
@@ -216,6 +215,7 @@ class ArcSample {
final bool largeArc;
final bool clockwise;
final double distance;
ArcSample(this.offset,
{this.largeArc = false, this.clockwise = false, this.distance = 0});