SvgRenderer

SvgRenderer

Main quirks-mode SVG rendering code.

Constructor

new SvgRenderer(canvasopt)

Create a quirks-mode SVG renderer for a particular canvas.

Parameters:
Name Type Attributes Description
canvas HTMLCanvasElement <optional>

An optional canvas element to draw to. If this is not provided, the renderer will create a new canvas.

Members

canvas

size

viewOffset

Methods

_createSVGElement(tagName) → (non-null) {DOMElement}

Helper to create an SVG element with the correct NS.

Parameters:
Name Type Description
tagName string

Tag name for the element.

Returns:

Element created.

Type
DOMElement

_draw()

Draw the SVG to a canvas.

_toString() → {string}

Serialize the active SVG DOM to a string.

Returns:

String representing current SVG data.

Type
string

_transformMeasurements()

Transform the measurements of the SVG. In Scratch 2.0, SVGs are drawn without respect to the width, height, and viewBox attribute on the tag. The exporter does output these properties - but they appear to be incorrect often. To address the incorrect measurements, we append the DOM to the document, and then use SVG's native getBBox to find the real drawn dimensions. This ensures things drawn in negative dimensions, outside the given viewBox, etc., are all eventually drawn to the canvas. I tried to do this several other ways: stripping the width/height/viewBox attributes and then drawing (Firefox won't draw anything), or inflating them and then measuring a canvas. But this seems to be a natural and performant way.

_transformText()

Transforms an SVG's text elements for Scratch 2.0 quirks. These quirks include:

  1. x and y properties are removed/ignored.
  2. Alignment is set to text-before-edge.
  3. Line-breaks are converted to explicit elements.
  4. Any required fonts are injected.

fromString(svgString, onFinishopt)

Load an SVG from a string and draw it. This will be parsed and transformed, and finally drawn. When drawing is finished, the onFinish callback is called.

Parameters:
Name Type Attributes Description
svgString string

String of SVG data to draw in quirks-mode.

onFinish function <optional>

Optional callback for when drawing finished.

getDrawRatio() → {number}

Get the drawing ratio, adjusted for HiDPI screens.

Returns:

Scale ratio to draw to canvases with.

Type
number