Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ 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

              
                <script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<p>Text: <input id='displayText' value="Mary had\na little wombat\nits fur\nas white as snow..."> </p>
<p>
  <span class='ipt'> Margin: <input id='margin' value='8,10,8,10' /></span>
  <span class='ipt'> Padding: <input id='padding' value='8,10,8,10' /></span>
  <span class='ipt'><button id='go' />Go</button></span> 
</p>
<p>
  <label for="marginAdjust">Adjust margin</label>
  <input id="marginAdjust" type="range" min="0" max="40" value="10">
  <span class='gap'></span>
  <label for="paddingAdjust">Adjust padding</label>
  <input id="paddingAdjust" type="range" min="0" max="40" value="10">
  <span class='gap'></span>
</p>
<p>
  <label for="fontsizeAdjust">Font size</label>
  <input id="fontsizeAdjust" type="range" min="1" max="79" value="20">
</p>
<div id="container"></div>
              
            
!

CSS

              
                body {
  margin: 20px;
  padding: 0;
  overflow: hidden;
  background-color: #f0f0f0;
}
#displayText {
  width: 550px;
}
              
            
!

JS

              
                // The following data structure contains the parameters used for the text. The marging and padding are 
// updated from the imputs & sliders.
const pos = {
  text: '',
  textColor: 'black',
  fontSize: 20,
  padFill: 'red', // the color for the text background
  padOpacity: 1, // the opacity for the text background
  marginFill: 'transparent', // the color for the margin background - set to 'transparent' for live
  marginOpacity: 0.5, // the opacity for the margin background
  marginStroke: 'red', // border for the outer box
  marginStrokeWidth: 0, // outer box border width
  x: 100, y : 70,  // position of text
  angle: 10,
  margin: { // reset later depending on inputs
    top: 0, 
    right: 0, 
    bottom: 0, 
    left: 0
  },
  padding: { // reset later depending on inputs
    top: 0, 
    right: 0, 
    bottom: 0, 
    left: 0    
  }
} 

const stage = new Konva.Stage({
        container: 'container',
        width: window.innerWidth,
        height: window.innerHeight 
      }),
      layer = new Konva.Layer(),
      
       // Create the text node we will clone this later for each text line
      textObj = new Konva.Text({
        text: '',
        fontFamily: 'Arial',
        fontSize: pos.fontSize,
        x: 0,
        y: 0,
        fill: pos.textColor,
        visible: false
      }),
    
      // Make a text node for measuring.
      textMeasure = textObj.clone(),
      
      group = new Konva.Group();

// Add layer to stage and group to layer
stage.add(layer);
layer.add(group);         
        

// function to do the drawing. Could easily be accomodated into a class 
function reset(opts)
{
  textMeasure.setAttrs({text: opts.text, fontSize: opts.fontSize}); // give the text to tje measuring shape.

  group.destroyChildren(); // clear out any previously created text & rects.

  // Set the position and rotation of the group
  group.setAttrs({
    x: opts.x - (opts.padding.left - opts.margin.left),
    y: opts.y - (opts.padding.top - opts.margin.top),
    rotation: pos.angle
  });  
 
  // loop round the lines in the text creating a margin/pad scenario for each line
  let textHeight,  top = 0;

  for (let i = 0; i < textMeasure.textArr.length; i = i + 1){
  
    const theText = textMeasure.textArr[i];
    
    // Get the height of the text line
    textHeight = Math.floor(textMeasure.lineHeight() * textMeasure.fontSize()); 
 
    // Make the text node for line i
    const text = textObj.clone({text: textMeasure.textArr[i].text, x: 0, y: top, fontSize: opts.fontSize, visible: true});

  // create the outer 'margin' rect, note the position is negatively offset for padding & margin 
  // and the width is sized from the dimensions of the text node plus 2 x (padding + margin).
  let rectMargin =   new Konva.Rect({
        x: -1 *  (opts.padding.left + opts.margin.left), 
        y: top - (opts.padding.top + opts.margin.top),
        width: text.width() + ((opts.padding.left + opts.padding.right) + (opts.margin.left + opts.margin.right)), 
        height: textHeight + ((opts.padding.top + opts.padding.bottom) + (opts.margin.top + opts.margin.bottom)),
        fill: opts.marginFill,
        opacity: opts.marginOpacity,
        stroke: opts.marginStroke,
        strokeWidth: opts.marginStrokeWidth
      })
 
  // create the inner 'padding' rect, note the position is offset for padding only
  // and the width is sized from the dimensions of the text node plus 2 x padding.
  let rectPadding =   new Konva.Rect({
      width: text.width() + opts.padding.left + opts.padding.right, 
      height: textHeight + (opts.padding.top + opts.padding.bottom),
      x: -1 *  opts.padding.left, 
      y: top - opts.padding.top,
      fill: opts.padFill,
      opacity: opts.padOpacity
  })
  
  group.add(rectMargin, rectPadding, text)

  // move the insert point down by the height of the line
  top = top - 1 + textHeight + opts.padding.top + opts.margin.top + opts.padding.bottom + opts.margin.bottom; 
  
}



}



// function to grab values from user inputs
function go()
{
  let m = $('#margin').val().split(','),
      p = $('#padding').val().split(',');

  for (let i = 0 ; i < 4; i = i + 1)
  {
    p[i] = parseInt(p[i], 10); // ensure we have numbers and not strings !
    m[i] = parseInt(m[i], 10);
  }

  // Object holding position and content info
  pos.padding = {
      top:p[0], 
      right:p[1], 
      bottom: p[2], 
      left: p[3]
    };
  pos.margin = {
    top:m[0], 
    right:m[1], 
    bottom: m[2], 
    left: m[3]
  };

  pos.text = $('#displayText').val();
  pos.text = pos.text.replace(/\\n/g, "\n")
  
reset(pos);
}


// click handler for go button
$('#go').on('click', function(e){
  go();
  
})

// Event listener for margin slider - refresh parameters when change occurs.
let lastMargin = $('#marginAdjust').val();
$('#marginAdjust').on('input', function(e){
  let m = $('#margin').val().split(','),
      newMargin = $('#marginAdjust').val(),
      inc = newMargin - lastMargin; 
  
  lastMargin = newMargin; // remember the current margin
   
  for (let i = 0 ; i < 4; i = i + 1)
  {
    let val = parseInt(m[i], 10) + inc
    m[i] = val < 0 ? 0 : val;
    
  }
  $('#margin').val(m.join(','))
  
  go();    
})
 
// Event listener for margin slider - refresh parameters when change occurs.
let lastPadding = $('#paddingAdjust').val();
$('#paddingAdjust').on('input', function(e){
  let p= $('#padding').val().split(','),
      newPadding = $('#paddingAdjust').val(),
      inc = newPadding - lastPadding; 
  
  lastPadding = newPadding; // remember the current padding
  
 
  for (let i = 0 ; i < 4; i = i + 1)
  { 
    let val = parseInt(p[i], 10) + inc
    p[i] = val < 0 ? 0 : val;
  }
  $('#padding').val(p.join(','))
  
  go();    
})

$('#fontsizeAdjust').on('input', function(e){

  pos.fontSize = parseInt($('#fontsizeAdjust').val(), 10);
  
  go();
})

// call go once to show on load
go();

              
            
!
999px

Console