@scratch/scratch-svg-renderer 11.0.0-UEPR-176
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +12 -0
- package/README.md +89 -0
- package/dist/node/scratch-svg-renderer.js +3 -0
- package/dist/node/scratch-svg-renderer.js.LICENSE.txt +417 -0
- package/dist/node/scratch-svg-renderer.js.map +1 -0
- package/dist/web/scratch-svg-renderer.js +3 -0
- package/dist/web/scratch-svg-renderer.js.LICENSE.txt +1 -0
- package/dist/web/scratch-svg-renderer.js.map +1 -0
- package/package.json +80 -0
- package/src/bitmap-adapter.js +156 -0
- package/src/fixup-svg-string.js +61 -0
- package/src/font-converter.js +38 -0
- package/src/font-inliner.js +50 -0
- package/src/index.js +22 -0
- package/src/load-svg-string.js +334 -0
- package/src/playground/index.html +132 -0
- package/src/sanitize-svg.js +104 -0
- package/src/serialize-svg-to-string.js +19 -0
- package/src/svg-element.js +71 -0
- package/src/svg-renderer.js +169 -0
- package/src/transform-applier.js +628 -0
- package/src/util/log.js +4 -0
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
const DOMPurify = require('isomorphic-dompurify');
|
|
2
|
+
const SvgElement = require('./svg-element');
|
|
3
|
+
const convertFonts = require('./font-converter');
|
|
4
|
+
const fixupSvgString = require('./fixup-svg-string');
|
|
5
|
+
const transformStrokeWidths = require('./transform-applier');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @param {SVGElement} svgTag the tag to search within
|
|
9
|
+
* @param {string} [tagName] svg tag to search for (or collect all elements if not given)
|
|
10
|
+
* @return {Array} a list of elements with the given tagname
|
|
11
|
+
*/
|
|
12
|
+
const collectElements = (svgTag, tagName) => {
|
|
13
|
+
const elts = [];
|
|
14
|
+
const collectElementsInner = domElement => {
|
|
15
|
+
if ((domElement.localName === tagName || typeof tagName === 'undefined') && domElement.getAttribute) {
|
|
16
|
+
elts.push(domElement);
|
|
17
|
+
}
|
|
18
|
+
for (let i = 0; i < domElement.childNodes.length; i++) {
|
|
19
|
+
collectElementsInner(domElement.childNodes[i]);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
collectElementsInner(svgTag);
|
|
23
|
+
return elts;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Fix SVGs to comply with SVG spec. Scratch 2 defaults to x2 = 0 when x2 is missing, but
|
|
28
|
+
* SVG defaults to x2 = 1 when missing.
|
|
29
|
+
* @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to
|
|
30
|
+
*/
|
|
31
|
+
const transformGradients = svgTag => {
|
|
32
|
+
const linearGradientElements = collectElements(svgTag, 'linearGradient');
|
|
33
|
+
|
|
34
|
+
// For each gradient element, supply x2 if necessary.
|
|
35
|
+
for (const gradientElement of linearGradientElements) {
|
|
36
|
+
if (!gradientElement.getAttribute('x2')) {
|
|
37
|
+
gradientElement.setAttribute('x2', '0');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Fix SVGs to match appearance in Scratch 2, which used nearest neighbor scaling for bitmaps
|
|
44
|
+
* within SVGs.
|
|
45
|
+
* @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to
|
|
46
|
+
*/
|
|
47
|
+
const transformImages = svgTag => {
|
|
48
|
+
const imageElements = collectElements(svgTag, 'image');
|
|
49
|
+
|
|
50
|
+
// For each image element, set image rendering to pixelated
|
|
51
|
+
const pixelatedImages = 'image-rendering: optimizespeed; image-rendering: pixelated;';
|
|
52
|
+
for (const elt of imageElements) {
|
|
53
|
+
if (elt.getAttribute('style')) {
|
|
54
|
+
elt.setAttribute('style',
|
|
55
|
+
`${pixelatedImages} ${elt.getAttribute('style')}`);
|
|
56
|
+
} else {
|
|
57
|
+
elt.setAttribute('style', pixelatedImages);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Transforms an SVG's text elements for Scratch 2.0 quirks.
|
|
64
|
+
* These quirks include:
|
|
65
|
+
* 1. `x` and `y` properties are removed/ignored.
|
|
66
|
+
* 2. Alignment is set to `text-before-edge`.
|
|
67
|
+
* 3. Line-breaks are converted to explicit <tspan> elements.
|
|
68
|
+
* 4. Any required fonts are injected.
|
|
69
|
+
* @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to
|
|
70
|
+
*/
|
|
71
|
+
const transformText = svgTag => {
|
|
72
|
+
// Collect all text elements into a list.
|
|
73
|
+
const textElements = [];
|
|
74
|
+
const collectText = domElement => {
|
|
75
|
+
if (domElement.localName === 'text') {
|
|
76
|
+
textElements.push(domElement);
|
|
77
|
+
}
|
|
78
|
+
for (let i = 0; i < domElement.childNodes.length; i++) {
|
|
79
|
+
collectText(domElement.childNodes[i]);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
collectText(svgTag);
|
|
83
|
+
convertFonts(svgTag);
|
|
84
|
+
// For each text element, apply quirks.
|
|
85
|
+
for (const textElement of textElements) {
|
|
86
|
+
// Remove x and y attributes - they are not used in Scratch.
|
|
87
|
+
textElement.removeAttribute('x');
|
|
88
|
+
textElement.removeAttribute('y');
|
|
89
|
+
// Set text-before-edge alignment:
|
|
90
|
+
// Scratch renders all text like this.
|
|
91
|
+
textElement.setAttribute('alignment-baseline', 'text-before-edge');
|
|
92
|
+
textElement.setAttribute('xml:space', 'preserve');
|
|
93
|
+
// If there's no font size provided, provide one.
|
|
94
|
+
if (!textElement.getAttribute('font-size')) {
|
|
95
|
+
textElement.setAttribute('font-size', '18');
|
|
96
|
+
}
|
|
97
|
+
let text = textElement.textContent;
|
|
98
|
+
|
|
99
|
+
// Fix line breaks in text, which are not natively supported by SVG.
|
|
100
|
+
// Only fix if text does not have child tspans.
|
|
101
|
+
// @todo this will not work for font sizes with units such as em, percent
|
|
102
|
+
// However, text made in scratch 2 should only ever export size 22 font.
|
|
103
|
+
const fontSize = parseFloat(textElement.getAttribute('font-size'));
|
|
104
|
+
const tx = 2;
|
|
105
|
+
let ty = 0;
|
|
106
|
+
let spacing = 1.2;
|
|
107
|
+
// Try to match the position and spacing of Scratch 2.0's fonts.
|
|
108
|
+
// Different fonts seem to use different line spacing.
|
|
109
|
+
// Scratch 2 always uses alignment-baseline=text-before-edge
|
|
110
|
+
// However, most SVG readers don't support this attribute
|
|
111
|
+
// or don't support it alongside use of tspan, so the translations
|
|
112
|
+
// here are to make up for that.
|
|
113
|
+
if (textElement.getAttribute('font-family') === 'Handwriting') {
|
|
114
|
+
spacing = 2;
|
|
115
|
+
ty = -11 * fontSize / 22;
|
|
116
|
+
} else if (textElement.getAttribute('font-family') === 'Scratch') {
|
|
117
|
+
spacing = 0.89;
|
|
118
|
+
ty = -3 * fontSize / 22;
|
|
119
|
+
} else if (textElement.getAttribute('font-family') === 'Curly') {
|
|
120
|
+
spacing = 1.38;
|
|
121
|
+
ty = -6 * fontSize / 22;
|
|
122
|
+
} else if (textElement.getAttribute('font-family') === 'Marker') {
|
|
123
|
+
spacing = 1.45;
|
|
124
|
+
ty = -6 * fontSize / 22;
|
|
125
|
+
} else if (textElement.getAttribute('font-family') === 'Sans Serif') {
|
|
126
|
+
spacing = 1.13;
|
|
127
|
+
ty = -3 * fontSize / 22;
|
|
128
|
+
} else if (textElement.getAttribute('font-family') === 'Serif') {
|
|
129
|
+
spacing = 1.25;
|
|
130
|
+
ty = -4 * fontSize / 22;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (textElement.transform.baseVal.numberOfItems === 0) {
|
|
134
|
+
const transform = svgTag.createSVGTransform();
|
|
135
|
+
textElement.transform.baseVal.appendItem(transform);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Right multiply matrix by a translation of (tx, ty)
|
|
139
|
+
const mtx = textElement.transform.baseVal.getItem(0).matrix;
|
|
140
|
+
mtx.e += (mtx.a * tx) + (mtx.c * ty);
|
|
141
|
+
mtx.f += (mtx.b * tx) + (mtx.d * ty);
|
|
142
|
+
|
|
143
|
+
if (text && textElement.childElementCount === 0) {
|
|
144
|
+
textElement.textContent = '';
|
|
145
|
+
const lines = text.split('\n');
|
|
146
|
+
text = '';
|
|
147
|
+
for (const line of lines) {
|
|
148
|
+
const tspanNode = SvgElement.create('tspan');
|
|
149
|
+
tspanNode.setAttribute('x', '0');
|
|
150
|
+
tspanNode.setAttribute('style', 'white-space: pre');
|
|
151
|
+
tspanNode.setAttribute('dy', `${spacing}em`);
|
|
152
|
+
tspanNode.textContent = line ? line : ' ';
|
|
153
|
+
textElement.appendChild(tspanNode);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Find the largest stroke width in the svg. If a shape has no
|
|
161
|
+
* `stroke` property, it has a stroke-width of 0. If it has a `stroke`,
|
|
162
|
+
* it is by default a stroke-width of 1.
|
|
163
|
+
* This is used to enlarge the computed bounding box, which doesn't take
|
|
164
|
+
* stroke width into account.
|
|
165
|
+
* @param {SVGSVGElement} rootNode The root SVG node to traverse.
|
|
166
|
+
* @return {number} The largest stroke width in the SVG.
|
|
167
|
+
*/
|
|
168
|
+
const findLargestStrokeWidth = rootNode => {
|
|
169
|
+
let largestStrokeWidth = 0;
|
|
170
|
+
const collectStrokeWidths = domElement => {
|
|
171
|
+
if (domElement.getAttribute) {
|
|
172
|
+
if (domElement.getAttribute('stroke')) {
|
|
173
|
+
largestStrokeWidth = Math.max(largestStrokeWidth, 1);
|
|
174
|
+
}
|
|
175
|
+
if (domElement.getAttribute('stroke-width')) {
|
|
176
|
+
largestStrokeWidth = Math.max(
|
|
177
|
+
largestStrokeWidth,
|
|
178
|
+
Number(domElement.getAttribute('stroke-width')) || 0
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
for (let i = 0; i < domElement.childNodes.length; i++) {
|
|
183
|
+
collectStrokeWidths(domElement.childNodes[i]);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
collectStrokeWidths(rootNode);
|
|
187
|
+
return largestStrokeWidth;
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Transform the measurements of the SVG.
|
|
192
|
+
* In Scratch 2.0, SVGs are drawn without respect to the width,
|
|
193
|
+
* height, and viewBox attribute on the tag. The exporter
|
|
194
|
+
* does output these properties - but they appear to be incorrect often.
|
|
195
|
+
* To address the incorrect measurements, we append the DOM to the
|
|
196
|
+
* document, and then use SVG's native `getBBox` to find the real
|
|
197
|
+
* drawn dimensions. This ensures things drawn in negative dimensions,
|
|
198
|
+
* outside the given viewBox, etc., are all eventually drawn to the canvas.
|
|
199
|
+
* I tried to do this several other ways: stripping the width/height/viewBox
|
|
200
|
+
* attributes and then drawing (Firefox won't draw anything),
|
|
201
|
+
* or inflating them and then measuring a canvas. But this seems to be
|
|
202
|
+
* a natural and performant way.
|
|
203
|
+
* @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to
|
|
204
|
+
*/
|
|
205
|
+
const transformMeasurements = svgTag => {
|
|
206
|
+
// Append the SVG dom to the document.
|
|
207
|
+
// This allows us to use `getBBox` on the page,
|
|
208
|
+
// which returns the full bounding-box of all drawn SVG
|
|
209
|
+
// elements, similar to how Scratch 2.0 did measurement.
|
|
210
|
+
const svgSpot = document.createElement('span');
|
|
211
|
+
// Since we're adding user-provided SVG to document.body,
|
|
212
|
+
// sanitizing is required. This should not affect bounding box calculation.
|
|
213
|
+
// outerHTML is attribute of Element (and not HTMLElement), so use it instead of
|
|
214
|
+
// calling serializer or toString()
|
|
215
|
+
// NOTE: svgTag remains untouched!
|
|
216
|
+
const rawValue = svgTag.outerHTML;
|
|
217
|
+
const sanitizedValue = DOMPurify.sanitize(rawValue, {
|
|
218
|
+
// Use SVG profile (no HTML elements)
|
|
219
|
+
USE_PROFILES: {svg: true},
|
|
220
|
+
// Remove some tags that Scratch does not use.
|
|
221
|
+
FORBID_TAGS: ['a', 'audio', 'canvas', 'video'],
|
|
222
|
+
// Allow data URI in image tags (e.g. SVGs converted from bitmap)
|
|
223
|
+
ADD_DATA_URI_TAGS: ['image']
|
|
224
|
+
});
|
|
225
|
+
let bbox;
|
|
226
|
+
try {
|
|
227
|
+
// Insert sanitized value.
|
|
228
|
+
svgSpot.innerHTML = sanitizedValue;
|
|
229
|
+
document.body.appendChild(svgSpot);
|
|
230
|
+
// Take the bounding box. We have to get elements via svgSpot
|
|
231
|
+
// because we added it via innerHTML.
|
|
232
|
+
bbox = svgSpot.children[0].getBBox();
|
|
233
|
+
} finally {
|
|
234
|
+
// Always destroy the element, even if, for example, getBBox throws.
|
|
235
|
+
document.body.removeChild(svgSpot);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// Enlarge the bbox from the largest found stroke width
|
|
239
|
+
// This may have false-positives, but at least the bbox will always
|
|
240
|
+
// contain the full graphic including strokes.
|
|
241
|
+
// If the width or height is zero however, don't enlarge since
|
|
242
|
+
// they won't have a stroke width that needs to be enlarged.
|
|
243
|
+
let halfStrokeWidth;
|
|
244
|
+
if (bbox.width === 0 || bbox.height === 0) {
|
|
245
|
+
halfStrokeWidth = 0;
|
|
246
|
+
} else {
|
|
247
|
+
halfStrokeWidth = findLargestStrokeWidth(svgTag) / 2;
|
|
248
|
+
}
|
|
249
|
+
const width = bbox.width + (halfStrokeWidth * 2);
|
|
250
|
+
const height = bbox.height + (halfStrokeWidth * 2);
|
|
251
|
+
const x = bbox.x - halfStrokeWidth;
|
|
252
|
+
const y = bbox.y - halfStrokeWidth;
|
|
253
|
+
|
|
254
|
+
// Set the correct measurements on the SVG tag
|
|
255
|
+
svgTag.setAttribute('width', width);
|
|
256
|
+
svgTag.setAttribute('height', height);
|
|
257
|
+
svgTag.setAttribute('viewBox',
|
|
258
|
+
`${x} ${y} ${width} ${height}`);
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Find all instances of a URL-referenced `stroke` in the svg. In 2.0, all gradient strokes
|
|
263
|
+
* have a round `stroke-linejoin` and `stroke-linecap`... for some reason.
|
|
264
|
+
* @param {SVGSVGElement} svgTag the SVG tag to apply the transformation to
|
|
265
|
+
*/
|
|
266
|
+
const setGradientStrokeRoundedness = svgTag => {
|
|
267
|
+
const elements = collectElements(svgTag);
|
|
268
|
+
|
|
269
|
+
for (const elt of elements) {
|
|
270
|
+
if (!elt.style) continue;
|
|
271
|
+
const stroke = elt.style.stroke || elt.getAttribute('stroke');
|
|
272
|
+
if (stroke && stroke.match(/^url\(#.*\)$/)) {
|
|
273
|
+
elt.style['stroke-linejoin'] = 'round';
|
|
274
|
+
elt.style['stroke-linecap'] = 'round';
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* In-place, convert passed SVG to something consistent that will be rendered the way we want them to be.
|
|
281
|
+
* @param {SVGSvgElement} svgTag root SVG node to operate upon
|
|
282
|
+
* @param {boolean} [fromVersion2] True if we should perform conversion from version 2 to version 3 svg.
|
|
283
|
+
*/
|
|
284
|
+
const normalizeSvg = (svgTag, fromVersion2) => {
|
|
285
|
+
if (fromVersion2) {
|
|
286
|
+
// Fix gradients. Scratch 2 exports no x2 when x2 = 0, but
|
|
287
|
+
// SVG default is that x2 is 1. This must be done before
|
|
288
|
+
// transformStrokeWidths since transformStrokeWidths affects
|
|
289
|
+
// gradients.
|
|
290
|
+
transformGradients(svgTag);
|
|
291
|
+
}
|
|
292
|
+
transformStrokeWidths(svgTag, window);
|
|
293
|
+
transformImages(svgTag);
|
|
294
|
+
if (fromVersion2) {
|
|
295
|
+
// Transform all text elements.
|
|
296
|
+
transformText(svgTag);
|
|
297
|
+
// Transform measurements.
|
|
298
|
+
transformMeasurements(svgTag);
|
|
299
|
+
// Fix stroke roundedness.
|
|
300
|
+
setGradientStrokeRoundedness(svgTag);
|
|
301
|
+
} else if (!svgTag.getAttribute('viewBox')) {
|
|
302
|
+
// Renderer expects a view box.
|
|
303
|
+
transformMeasurements(svgTag);
|
|
304
|
+
} else if (!svgTag.getAttribute('width') || !svgTag.getAttribute('height')) {
|
|
305
|
+
svgTag.setAttribute('width', svgTag.viewBox.baseVal.width);
|
|
306
|
+
svgTag.setAttribute('height', svgTag.viewBox.baseVal.height);
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Load an SVG string and normalize it. All the steps before drawing/measuring.
|
|
312
|
+
* Currently, this will normalize stroke widths (see transform-applier.js) and render all embedded images pixelated.
|
|
313
|
+
* The returned SVG will be guaranteed to always have a `width`, `height` and `viewBox`.
|
|
314
|
+
* In addition, if the `fromVersion2` parameter is `true`, several "quirks-mode" transformations will be applied which
|
|
315
|
+
* mimic Scratch 2.0's SVG rendering.
|
|
316
|
+
* @param {!string} svgString String of SVG data to draw in quirks-mode.
|
|
317
|
+
* @param {boolean} [fromVersion2] True if we should perform conversion from version 2 to version 3 svg.
|
|
318
|
+
* @return {SVGSVGElement} The normalized SVG element.
|
|
319
|
+
*/
|
|
320
|
+
const loadSvgString = (svgString, fromVersion2) => {
|
|
321
|
+
// Parse string into SVG XML.
|
|
322
|
+
const parser = new DOMParser();
|
|
323
|
+
svgString = fixupSvgString(svgString);
|
|
324
|
+
const svgDom = parser.parseFromString(svgString, 'text/xml');
|
|
325
|
+
if (svgDom.childNodes.length < 1 ||
|
|
326
|
+
svgDom.documentElement.localName !== 'svg') {
|
|
327
|
+
throw new Error('Document does not appear to be SVG.');
|
|
328
|
+
}
|
|
329
|
+
const svgTag = svgDom.documentElement;
|
|
330
|
+
normalizeSvg(svgTag, fromVersion2);
|
|
331
|
+
return svgTag;
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
module.exports = loadSvgString;
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8">
|
|
5
|
+
<title>Scratch SVG rendering playground</title>
|
|
6
|
+
<style>
|
|
7
|
+
.result {
|
|
8
|
+
background-color:gray;
|
|
9
|
+
}
|
|
10
|
+
#reference {
|
|
11
|
+
display:inline-block;
|
|
12
|
+
font-size:0;
|
|
13
|
+
}
|
|
14
|
+
.column {
|
|
15
|
+
display:inline-block;
|
|
16
|
+
}
|
|
17
|
+
</style>
|
|
18
|
+
</head>
|
|
19
|
+
<body>
|
|
20
|
+
<p>
|
|
21
|
+
<input type="file" id="svg-file-upload", accept="image/svg+xml">
|
|
22
|
+
</p>
|
|
23
|
+
<p>
|
|
24
|
+
<label for="render-scale">Scale:</label>
|
|
25
|
+
<input type="range" style="width:50%;" id="render-scale" value="1" min="0.5" max="3" step="any">
|
|
26
|
+
<label for="render-scale" id="scale-display"></label>
|
|
27
|
+
</p>
|
|
28
|
+
<p>
|
|
29
|
+
<input type="button" id="trigger-render" value="Render">
|
|
30
|
+
<label for="shouldRenderReference">
|
|
31
|
+
<input type="checkbox" id="shouldRenderReference" checked />
|
|
32
|
+
Render Reference?
|
|
33
|
+
</label>
|
|
34
|
+
</p>
|
|
35
|
+
|
|
36
|
+
<div class="columns">
|
|
37
|
+
<div class="column">
|
|
38
|
+
<div>Rendered Result</div>
|
|
39
|
+
<canvas id="render-canvas" class="result"></canvas>
|
|
40
|
+
</div>
|
|
41
|
+
<div class="column">
|
|
42
|
+
<div>Reference</div>
|
|
43
|
+
<span id="reference"></span>
|
|
44
|
+
</div>
|
|
45
|
+
</div>
|
|
46
|
+
<div class="columns">
|
|
47
|
+
<div class="column">
|
|
48
|
+
<div>Rendered Content</div>
|
|
49
|
+
<textarea id="renderedContent" wrap="off" cols="50" rows="50"></textarea>
|
|
50
|
+
</div>
|
|
51
|
+
<div class="column">
|
|
52
|
+
<div>Reference</div>
|
|
53
|
+
<span id="reference"></span>
|
|
54
|
+
<textarea id="referenceContent" wrap="off" cols="50" rows="50"></textarea>
|
|
55
|
+
</div>
|
|
56
|
+
</div>
|
|
57
|
+
|
|
58
|
+
<script src="scratch-svg-renderer.js"></script>
|
|
59
|
+
<script>
|
|
60
|
+
const renderCanvas = document.getElementById("render-canvas");
|
|
61
|
+
const referenceImage = document.getElementById("reference");
|
|
62
|
+
const fileChooser = document.getElementById("svg-file-upload");
|
|
63
|
+
const scaleSlider = document.getElementById("render-scale");
|
|
64
|
+
const scaleDisplay = document.getElementById("scale-display");
|
|
65
|
+
const renderButton = document.getElementById("trigger-render");
|
|
66
|
+
|
|
67
|
+
const renderer = new ScratchSVGRenderer.SVGRenderer(renderCanvas);
|
|
68
|
+
|
|
69
|
+
let loadedSVGString = "";
|
|
70
|
+
|
|
71
|
+
if (fileChooser.value) {
|
|
72
|
+
loadSVGString();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function renderSVGString() {
|
|
76
|
+
if (renderer.loaded) {
|
|
77
|
+
renderer.draw(parseFloat(scaleSlider.value));
|
|
78
|
+
}
|
|
79
|
+
renderedContent.value = renderer.toString(true);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function updateReferenceImage() {
|
|
83
|
+
referenceImage.innerHTML = loadedSVGString;
|
|
84
|
+
scalePercent = (parseFloat(scaleSlider.value) * 100) + "%"
|
|
85
|
+
referenceSVG = referenceImage.children[0];
|
|
86
|
+
referenceSVG.style.width = referenceSVG.style.height = scalePercent;
|
|
87
|
+
referenceSVG.classList.add("result");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function readFileAsText(file) {
|
|
91
|
+
return new Promise((res, rej) => {
|
|
92
|
+
const reader = new FileReader();
|
|
93
|
+
|
|
94
|
+
reader.onload = function(event) {
|
|
95
|
+
res(reader.result);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
reader.onerror = console.log;
|
|
99
|
+
|
|
100
|
+
reader.readAsText(file);
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function loadSVGString() {
|
|
105
|
+
readFileAsText(fileChooser.files[0]).then(str => {
|
|
106
|
+
loadedSVGString = str;
|
|
107
|
+
renderer.loadSVG(str, false);
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function renderLoadedString() {
|
|
112
|
+
renderSVGString();
|
|
113
|
+
referenceContent.value = loadedSVGString;
|
|
114
|
+
shouldRenderReference.checked && updateReferenceImage();
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function scaleSliderChanged() {
|
|
118
|
+
renderLoadedString();
|
|
119
|
+
scaleDisplay.innerText = scaleSlider.value;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
fileChooser.addEventListener("change", loadSVGString);
|
|
123
|
+
|
|
124
|
+
scaleSlider.addEventListener("change", scaleSliderChanged);
|
|
125
|
+
scaleSlider.addEventListener("input", scaleSliderChanged);
|
|
126
|
+
|
|
127
|
+
renderButton.addEventListener("click", (event => {
|
|
128
|
+
renderLoadedString();
|
|
129
|
+
}));
|
|
130
|
+
</script>
|
|
131
|
+
</body>
|
|
132
|
+
</html>
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileOverview Sanitize the content of an SVG aggressively, to make it as safe
|
|
3
|
+
* as possible
|
|
4
|
+
*/
|
|
5
|
+
const fixupSvgString = require('./fixup-svg-string');
|
|
6
|
+
const {generate, parse, walk} = require('css-tree');
|
|
7
|
+
const DOMPurify = require('isomorphic-dompurify');
|
|
8
|
+
|
|
9
|
+
const sanitizeSvg = {};
|
|
10
|
+
|
|
11
|
+
DOMPurify.addHook(
|
|
12
|
+
'beforeSanitizeAttributes',
|
|
13
|
+
currentNode => {
|
|
14
|
+
|
|
15
|
+
if (currentNode && currentNode.href && currentNode.href.baseVal) {
|
|
16
|
+
const href = currentNode.href.baseVal.replace(/\s/g, '');
|
|
17
|
+
// "data:" and "#" are valid hrefs
|
|
18
|
+
if ((href.slice(0, 5) !== 'data:') && (href.slice(0, 1) !== '#')) {
|
|
19
|
+
|
|
20
|
+
if (currentNode.attributes.getNamedItem('xlink:href')) {
|
|
21
|
+
currentNode.attributes.removeNamedItem('xlink:href');
|
|
22
|
+
delete currentNode['xlink:href'];
|
|
23
|
+
}
|
|
24
|
+
if (currentNode.attributes.getNamedItem('href')) {
|
|
25
|
+
currentNode.attributes.removeNamedItem('href');
|
|
26
|
+
delete currentNode.href;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return currentNode;
|
|
31
|
+
}
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
DOMPurify.addHook(
|
|
35
|
+
'uponSanitizeElement',
|
|
36
|
+
(node, data) => {
|
|
37
|
+
if (data.tagName === 'style') {
|
|
38
|
+
const ast = parse(node.textContent);
|
|
39
|
+
let isModified = false;
|
|
40
|
+
// Remove any @import rules as it could leak HTTP requests
|
|
41
|
+
walk(ast, (astNode, item, list) => {
|
|
42
|
+
if (astNode.type === 'Atrule' && astNode.name === 'import') {
|
|
43
|
+
list.remove(item);
|
|
44
|
+
isModified = true;
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
if (isModified) {
|
|
48
|
+
node.textContent = generate(ast);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
// Use JS implemented TextDecoder and TextEncoder if it is not provided by the
|
|
55
|
+
// browser.
|
|
56
|
+
let _TextDecoder;
|
|
57
|
+
let _TextEncoder;
|
|
58
|
+
if (typeof TextDecoder === 'undefined' || typeof TextEncoder === 'undefined') {
|
|
59
|
+
// Wait to require the text encoding polyfill until we know it's needed.
|
|
60
|
+
// eslint-disable-next-line global-require
|
|
61
|
+
const encoding = require('fastestsmallesttextencoderdecoder');
|
|
62
|
+
_TextDecoder = encoding.TextDecoder;
|
|
63
|
+
_TextEncoder = encoding.TextEncoder;
|
|
64
|
+
} else {
|
|
65
|
+
_TextDecoder = TextDecoder;
|
|
66
|
+
_TextEncoder = TextEncoder;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Load an SVG Uint8Array of bytes and "sanitize" it
|
|
71
|
+
* @param {!Uint8Array} rawData unsanitized SVG daata
|
|
72
|
+
* @return {Uint8Array} sanitized SVG data
|
|
73
|
+
*/
|
|
74
|
+
sanitizeSvg.sanitizeByteStream = function (rawData) {
|
|
75
|
+
const decoder = new _TextDecoder();
|
|
76
|
+
const encoder = new _TextEncoder();
|
|
77
|
+
const sanitizedText = sanitizeSvg.sanitizeSvgText(decoder.decode(rawData));
|
|
78
|
+
return encoder.encode(sanitizedText);
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Load an SVG string and "sanitize" it. This is more aggressive than the handling in
|
|
83
|
+
* fixup-svg-string.js, and thus more risky; there are known examples of SVGs that
|
|
84
|
+
* it will clobber. We use DOMPurify's svg profile, which restricts many types of tag.
|
|
85
|
+
* @param {!string} rawSvgText unsanitized SVG string
|
|
86
|
+
* @return {string} sanitized SVG text
|
|
87
|
+
*/
|
|
88
|
+
sanitizeSvg.sanitizeSvgText = function (rawSvgText) {
|
|
89
|
+
let sanitizedText = DOMPurify.sanitize(rawSvgText, {
|
|
90
|
+
USE_PROFILES: {svg: true}
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// Remove partial XML comment that is sometimes left in the HTML
|
|
94
|
+
const badTag = sanitizedText.indexOf(']>');
|
|
95
|
+
if (badTag >= 0) {
|
|
96
|
+
sanitizedText = sanitizedText.substring(5, sanitizedText.length);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// also use our custom fixup rules
|
|
100
|
+
sanitizedText = fixupSvgString(sanitizedText);
|
|
101
|
+
return sanitizedText;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
module.exports = sanitizeSvg;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const inlineSvgFonts = require('./font-inliner');
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Serialize a given SVG DOM to a string.
|
|
5
|
+
* @param {SVGSVGElement} svgTag The SVG element to serialize.
|
|
6
|
+
* @param {?boolean} shouldInjectFonts True if fonts should be included in the SVG as
|
|
7
|
+
* base64 data.
|
|
8
|
+
* @returns {string} String representing current SVG data.
|
|
9
|
+
*/
|
|
10
|
+
const serializeSvgToString = (svgTag, shouldInjectFonts) => {
|
|
11
|
+
const serializer = new XMLSerializer();
|
|
12
|
+
let string = serializer.serializeToString(svgTag);
|
|
13
|
+
if (shouldInjectFonts) {
|
|
14
|
+
string = inlineSvgFonts(string);
|
|
15
|
+
}
|
|
16
|
+
return string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
module.exports = serializeSvgToString;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/* Adapted from
|
|
2
|
+
* Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
|
|
3
|
+
* http://paperjs.org/
|
|
4
|
+
*
|
|
5
|
+
* Copyright (c) 2011 - 2016, Juerg Lehni & Jonathan Puckey
|
|
6
|
+
* http://scratchdisk.com/ & http://jonathanpuckey.com/
|
|
7
|
+
*
|
|
8
|
+
* Distributed under the MIT license. See LICENSE file for details.
|
|
9
|
+
*
|
|
10
|
+
* All rights reserved.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @name SvgElement
|
|
15
|
+
* @namespace
|
|
16
|
+
* @private
|
|
17
|
+
*/
|
|
18
|
+
class SvgElement {
|
|
19
|
+
// SVG related namespaces
|
|
20
|
+
static get svg () {
|
|
21
|
+
return 'http://www.w3.org/2000/svg';
|
|
22
|
+
}
|
|
23
|
+
static get xmlns () {
|
|
24
|
+
return 'http://www.w3.org/2000/xmlns';
|
|
25
|
+
}
|
|
26
|
+
static get xlink () {
|
|
27
|
+
return 'http://www.w3.org/1999/xlink';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Mapping of attribute names to required namespaces:
|
|
31
|
+
static attributeNamespace () {
|
|
32
|
+
return {
|
|
33
|
+
'href': SvgElement.xlink,
|
|
34
|
+
'xlink': SvgElement.xmlns,
|
|
35
|
+
// Only the xmlns attribute needs the trailing slash. See #984
|
|
36
|
+
'xmlns': `${SvgElement.xmlns}/`,
|
|
37
|
+
// IE needs the xmlns namespace when setting 'xmlns:xlink'. See #984
|
|
38
|
+
'xmlns:xlink': `${SvgElement.xmlns}/`
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
static create (tag, attributes, formatter) {
|
|
43
|
+
return SvgElement.set(document.createElementNS(SvgElement.svg, tag), attributes, formatter);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
static get (node, name) {
|
|
47
|
+
const namespace = SvgElement.attributeNamespace[name];
|
|
48
|
+
const value = namespace ?
|
|
49
|
+
node.getAttributeNS(namespace, name) :
|
|
50
|
+
node.getAttribute(name);
|
|
51
|
+
return value === 'null' ? null : value;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
static set (node, attributes, formatter) {
|
|
55
|
+
for (const name in attributes) {
|
|
56
|
+
let value = attributes[name];
|
|
57
|
+
const namespace = SvgElement.attributeNamespace[name];
|
|
58
|
+
if (typeof value === 'number' && formatter) {
|
|
59
|
+
value = formatter.number(value);
|
|
60
|
+
}
|
|
61
|
+
if (namespace) {
|
|
62
|
+
node.setAttributeNS(namespace, name, value);
|
|
63
|
+
} else {
|
|
64
|
+
node.setAttribute(name, value);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return node;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
module.exports = SvgElement;
|