Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="controls">
 <label for="stage-resize">Set stage size: </label>
  <select name="stage-resize" id="stage-resize">
    <option value="800x450">800x450</option>
    <option value="800x800">800x800</option>
    <option value="1024x576">1024x576</option>
    <option value="400x600">400x600</option>
    <option value="1280x720">1280x720</option>
  </select> 
</div>

<svg width="800" height="450" viewBox="0 0 800 450">
  <path class="path"/>
</svg>
              
            
!

CSS

              
                body
  background: black
  color: white
  font-family: 'helvetica neue', helvetica, arial, sans-serif
.controls, svg
  position: relative
  display: block
  margin-top: 10px
svg
  background: white
path
  stroke: red
  stroke-width: 1
  fill: none
              
            
!

JS

              
                let p = "M0 0 l800 79 -800 59 800 66 -800 62 800 71 -800 77 400 51",
    stage = document.querySelector('svg'),
    path = document.querySelector('.path');

function fillStage() {
  
  let $svgRoot    = $(stage),
      $path       = $(path),
      oldPathDStr = $path.attr("d");

  // Calculate the transformation required.
  var obj = getTranslationAndScaling($svgRoot, $path);
  var pathTranslX = obj.pathTranslX;
  var pathTranslY = obj.pathTranslY;
  var scale       = obj.scale;
  
  // The code following this line mutates the actual svg path.
  // Calculate the path "d" attributes parameters.
  var newPathDStr = getTransformedPathDStr(oldPathDStr, pathTranslX, pathTranslY, scale);

  // Apply the new "d" attribute to the path, transforming it.
  $path.attr("d", newPathDStr);

  console.log("Altered 'd' attribute of path: " + newPathDStr);
}

function resizeStage(obj) {
  stage.setAttributeNS(null,'width',obj.wd);
  stage.setAttributeNS(null,'height',obj.ht);
  stage.setAttributeNS(null,'viewBox',`0 0 ${obj.wd} ${obj.ht}`);
  fillStage();
}

$('select#stage-resize').on('change', function(){
  let dims = $(this).val().split('x');
  resizeStage({wd: parseInt(dims[0]), ht: parseInt(dims[1])});
});


path.setAttributeNS(null, 'd', p);

// Calculate the transformation, i.e. the translation and scaling, required
// to get the path to fill the svg area. Note that this assumes uniform
// scaling, a path that has no other transforms applied to it, and no
// differences between the svg viewport and viewBox dimensions.
function getTranslationAndScaling($svgRoot, $path) {
  var svgWdth = $svgRoot.attr("width" );
  var svgHght = $svgRoot.attr("height");

  var origPathBoundingBox = $path[0].getBBox();

  var origPathWdth = origPathBoundingBox.width ;
  var origPathHght = origPathBoundingBox.height;
  var origPathX    = origPathBoundingBox.x     ;
  var origPathY    = origPathBoundingBox.y     ;

  // how much bigger is the svg root element
  // relative to the path in each dimension?
  var scaleBasedOnWdth = svgWdth / origPathWdth;
  var scaleBasedOnHght = svgHght / origPathHght;

  // of the scaling factors determined in each dimension,
  // use the smaller one; otherwise portions of the path
  // will lie outside the viewport (correct term?)
  var scale = Math.min(scaleBasedOnWdth, scaleBasedOnHght);

  // calculate the bounding box parameters
  // after the path has been scaled relative to the origin
  // but before any subsequent translations have been applied

  var scaledPathX    = origPathX    * scale;
  var scaledPathY    = origPathY    * scale;
  var scaledPathWdth = origPathWdth * scale;
  var scaledPathHght = origPathHght * scale;

  // calculate the centre points of the scaled but untranslated path
  // as well as of the svg root element

  var scaledPathCentreX = scaledPathX + (scaledPathWdth / 2);
  var scaledPathCentreY = scaledPathY + (scaledPathHght / 2);
  var    svgRootCentreX = 0           + (svgWdth        / 2);
  var    svgRootCentreY = 0           + (svgHght        / 2);

  // calculate translation required to centre the path
  // on the svg root element

  var pathTranslX = parseFloat((svgRootCentreX - scaledPathCentreX).toFixed(3));
  var pathTranslY = parseFloat((svgRootCentreY - scaledPathCentreY).toFixed(3));

  return {pathTranslX, pathTranslY, scale};
}
  
function getTransformedPathDStr(oldPathDStr, pathTranslX, pathTranslY, scale) {

  // constants to help keep track of the types of SVG commands in the path
  var BOTH_X_AND_Y   = 1;
  var JUST_X         = 2;
  var JUST_Y         = 3;
  var NONE           = 4;
  var ELLIPTICAL_ARC = 5;
  var ABSOLUTE       = 6;
  var RELATIVE       = 7;

  // two parallel arrays, with each element being one component of the
  // "d" attribute of the SVG path, with one component being either
  // an instruction (e.g. "M" for moveto, etc.) or numerical value
  // for either an x or y coordinate
  var oldPathDArr = getArrayOfPathDComponents(oldPathDStr);
  var newPathDArr = [];

  var commandParams, absOrRel, oldPathDComp, newPathDComp;

  // element index
  var idx = 0;

  while (idx < oldPathDArr.length) {
    var oldPathDComp = oldPathDArr[idx];
    if (/^[A-Za-z]$/.test(oldPathDComp)) { // component is a single letter, i.e. an svg path command
      newPathDArr[idx] = oldPathDArr[idx];
      switch (oldPathDComp.toUpperCase()) {
        case "A": // elliptical arc command...the most complicated one
          commandParams = ELLIPTICAL_ARC;
          break;
        case "H": // horizontal line; requires only an x-coordinate
          commandParams = JUST_X;
          break;
        case "V": // vertical line; requires only a y-coordinate
          commandParams = JUST_Y;
          break;
        case "Z": // close the path
          commandParams = NONE;
          break;
        default: // all other commands; all of them require both x and y coordinates
          commandParams = BOTH_X_AND_Y;
      }
      absOrRel = ((oldPathDComp === oldPathDComp.toUpperCase()) ? ABSOLUTE : RELATIVE);
      // lowercase commands are relative, uppercase are absolute
      idx += 1;
    } else { // if the component is not a letter, then it is a numeric value
      var translX, translY;
      if (absOrRel === ABSOLUTE) { // the translation is required for absolute commands...
        translX = pathTranslX;
        translY = pathTranslY;
      } else if (absOrRel === RELATIVE) { // ...but not relative ones
        translX = 0;
        translY = 0;
      }
      switch (commandParams) {
        // figure out which of the numeric values following an svg command
        // are required, and then transform the numeric value(s) from the
        // original path d-attribute and place it in the same location in the
        // array that will eventually become the d-attribute for the new path
        case BOTH_X_AND_Y:
          newPathDArr[idx    ] = parseFloat(Number(oldPathDArr[idx    ]) * scale + translX).toFixed(3);
          newPathDArr[idx + 1] = parseFloat(Number(oldPathDArr[idx + 1]) * scale + translY).toFixed(3);
          idx += 2;
          break;
        case JUST_X:
          newPathDArr[idx    ] = parseFloat(Number(oldPathDArr[idx    ]) * scale + translX).toFixed(3);
          idx += 1;
          break;
        case JUST_Y:
          newPathDArr[idx    ] = parseFloat(Number(oldPathDArr[idx    ]) * scale + translY).toFixed(3);
          idx += 1;
          break;
        case ELLIPTICAL_ARC:
          // the elliptical arc has x and y values in the first and second as well as
          // the 6th and 7th positions following the command; the intervening values
          // are not affected by the transformation and so can simply be copied
          newPathDArr[idx    ] = Number(oldPathDArr[idx    ]) * scale + translX;
          newPathDArr[idx + 1] = Number(oldPathDArr[idx + 1]) * scale + translY;
          newPathDArr[idx + 2] = Number(oldPathDArr[idx + 2])                        ;
          newPathDArr[idx + 3] = Number(oldPathDArr[idx + 3])                        ;
          newPathDArr[idx + 4] = Number(oldPathDArr[idx + 4])                        ;
          newPathDArr[idx + 5] = Number(oldPathDArr[idx + 5]) * scale + translX;
          newPathDArr[idx + 6] = Number(oldPathDArr[idx + 6]) * scale + translY;
          idx += 7;
          break;
        case NONE:
          throw new Error('numeric value should not follow the SVG Z/z command');
          break;
      }
    }
  }
  // return newPathDArr.join(" ");
  let returnPath = "";
  // remove spaces between letters and subsequent number
  for( let i = 0; i < newPathDArr.length; i++ ) {
    if( isNaN(newPathDArr[i]) ) {
      returnPath += newPathDArr[i]+newPathDArr[i+1];
      i++;
    } else {
      returnPath += " "+newPathDArr[i];
    }
  }
  return returnPath;
}

function getArrayOfPathDComponents(str) {
  // assuming the string from the d-attribute of the path has all components
  // separated by a single space, then create an array of components by
  // simply splitting the string at those spaces
  str = standardizePathDStrFormat(str);
  return str.split(" ");
}

function standardizePathDStrFormat(str) {
  // The SVG standard is flexible with respect to how path d-strings are
  // formatted but this makes parsing them more difficult. This function ensures
  // that all SVG path d-string components (i.e. both commands and values) are
  // separated by a single space.
  return str
    .replace(/,/g         , " "   )  // replace each comma with a space
    .replace(/-/g         , " -"  )  // precede each minus sign with a space
    .replace(/([A-Za-z])/g, " $1 ")  // sandwich each   letter between 2 spaces
    .replace(/  /g        , " "   )  // collapse repeated spaces to a single space
    .replace(/ ([Ee]) /g  , "$1"  )  // remove flanking spaces around exponent symbols
    .replace(/^ /g        , ""    )  // trim any leading space
    .replace(/ $/g        , ""    ); // trim any tailing space
}
              
            
!
999px

Console