Skip to content

Commit

Permalink
Merge pull request #87 from adroitwhiz/fix-linejoin
Browse files Browse the repository at this point in the history
Set stroke-linejoin and stroke-linecap to "round" for gradient strokes in 2.0 SVGs
  • Loading branch information
fsih committed Feb 4, 2020
2 parents ec35ed3 + e6cc9fb commit 67a513c
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions src/svg-renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ class SvgRenderer {
this._transformText();
// Transform measurements.
this._transformMeasurements();
// Fix stroke roundedness.
this._setGradientStrokeRoundedness();
} else if (!this._svgTag.getAttribute('viewBox')) {
// Renderer expects a view box.
this._transformMeasurements();
Expand Down Expand Up @@ -242,13 +244,13 @@ class SvgRenderer {
}

/**
* @param {string} tagName svg tag to search for
* @param {string} [tagName] svg tag to search for (or collect all elements if not given)
* @return {Array} a list of elements with the given tagname in _svgTag
*/
_collectElements (tagName) {
const elts = [];
const collectElements = domElement => {
if (domElement.localName === tagName) {
if ((domElement.localName === tagName || typeof tagName === 'undefined') && domElement.getAttribute) {
elts.push(domElement);
}
for (let i = 0; i < domElement.childNodes.length; i++) {
Expand Down Expand Up @@ -281,7 +283,7 @@ class SvgRenderer {
_transformImages () {
const imageElements = this._collectElements('image');

// For each image element, set image rendering to pixelated"
// For each image element, set image rendering to pixelated
const pixelatedImages = 'image-rendering: optimizespeed; image-rendering: pixelated;';
for (const elt of imageElements) {
if (elt.getAttribute('style')) {
Expand Down Expand Up @@ -324,6 +326,23 @@ class SvgRenderer {
return largestStrokeWidth;
}

/**
* Find all instances of a URL-referenced `stroke` in the svg. In 2.0, all gradient strokes
* have a round `stroke-linejoin` and `stroke-linecap`... for some reason.
*/
_setGradientStrokeRoundedness () {
const elements = this._collectElements();

for (const elt of elements) {
if (!elt.style) continue;
const stroke = elt.style.stroke || elt.getAttribute('stroke');
if (stroke && stroke.match(/^url\(#.*\)$/)) {
elt.style['stroke-linejoin'] = 'round';
elt.style['stroke-linecap'] = 'round';
}
}
}

/**
* Transform the measurements of the SVG.
* In Scratch 2.0, SVGs are drawn without respect to the width,
Expand Down

0 comments on commit 67a513c

Please sign in to comment.