Created
January 3, 2018 12:11
-
-
Save xErik/0fa2552c8509fb155d7bc731ba361b42 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SVG.Text with added functionality of measing the pixel width server side using NODE. | |
// | |
// Depends mainly on 'svg.js' and 'string-pixel-width'. | |
// 'Check string-pixel-width' on npmjs.org for supported fonts. | |
// | |
// COMPLETE EXAMPLE | |
// | |
// const window = require('svgdom'); | |
// const SVG = require('svg.js')(window); | |
// const document = window.document; | |
// const draw = SVG(document.documentElement); | |
// var pixelWidth = require('string-pixel-width'); | |
// | |
// SVG.extend(SVG.Text, { | |
// pixelWidth: function() { | |
// var arr = this.text().split('\n'); | |
// var family = this.font().family; | |
// var size = this.font().size; | |
// if(family === undefined) { | |
// throw('Font-family is not set.'); | |
// } | |
// if(size === undefined) { | |
// throw('Font-size is not set.'); | |
// } | |
// var length = null; | |
// var lengthMax = -1; | |
// for (var i = 0; i < arr.length; i++) { | |
// length = pixelWidth(arr[i], { | |
// font: family, | |
// size: size | |
// }); | |
// if (length > lengthMax) { | |
// lengthMax = length; | |
// } | |
// } | |
// return lengthMax; | |
// } | |
// }); | |
// | |
// var text = draw.text(function(add) { | |
// add.tspan('Lorem ipsum dolor sit amet ').newLine(); | |
// add.tspan('consectetur').fill('#f06'); | |
// add.tspan('.'); | |
// add.tspan('Cras sodales imperdiet auctor.').newLine(); | |
// add.tspan('Nunc ultrices lectus at erat').newLine(); | |
// add.tspan('dictum pharetra elementum ante').newLine(); | |
// }).font({ | |
// family: 'courier new', | |
// size: 18 | |
// }); | |
// | |
// // Finds the longest text line and calcualtes its pixel width. | |
// console.log( text.pixelWidth() ); // Result: 421.2 | |
SVG.extend(SVG.Text, { | |
pixelWidth: function() { | |
var arr = this.text().split('\n'); | |
var family = this.font().family; | |
var size = this.font().size; | |
if(family === undefined) { | |
throw('Font-family is not set.'); | |
} | |
if(size === undefined) { | |
throw('Font-size is not set.'); | |
} | |
var length = null; | |
var lengthMax = -1; | |
for (var i = 0; i < arr.length; i++) { | |
length = pixelWidth(arr[i], { | |
font: family, | |
size: size | |
}); | |
if (length > lengthMax) { | |
lengthMax = length; | |
} | |
} | |
return lengthMax; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment