Skip to content

Instantly share code, notes, and snippets.

@souporserious
Created October 2, 2017 07:47
Show Gist options
  • Save souporserious/d5fb04e9ca3e4bb10ab4e58d00aac758 to your computer and use it in GitHub Desktop.
Save souporserious/d5fb04e9ca3e4bb10ab4e58d00aac758 to your computer and use it in GitHub Desktop.
import React, { Component, PureComponent, Children, cloneElement } from 'react'
import ReactDOM from 'react-dom'
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
const fontWeight = 400
const fontSize = '16px'
const fontFamily = 'Lato'
const lineHeight = '20px'
context.font = `${fontWeight} ${fontSize} ${fontFamily}`
function getLines(text, maxWidth) {
const words = text.split(' ')
const lines = []
let currentLine = words[0]
for (var i = 1; i < words.length; i++) {
const word = words[i]
const width = context.measureText(currentLine + ' ' + word).width
if (width < maxWidth) {
currentLine += ' ' + word
} else {
lines.push(currentLine)
currentLine = word
}
}
lines.push(currentLine)
return {
lines,
height: lines.length * parseInt(lineHeight, 10),
}
}
function Text({
children,
measured = true,
width = window.innerWidth,
...props
}) {
const { lines, height } = getLines(children, width)
return (
<Box style={{ height }} {...props}>
{measured
? lines.map((line, index) => <div key={index}>{line}</div>)
: children}
</Box>
)
}
const str = `Contrary to popular belief, Lorem Ipsum is not simply random text. It
has roots in a piece of classical Latin literature from 45 BC, making
it over 2000 years old. Richard McClintock, a Latin professor at
Hampden-Sydney College in Virginia, looked up one of the more obscure
Latin words, consectetur, from a Lorem Ipsum passage, and going
through the cites of the word in classical literature, discovered the
undoubtable source. Lorem Ipsum comes from sections 1.10.32 and
1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and
Evil) by Cicero, written in 45 BC. This book is a treatise on the
theory of ethics, very popular during the Renaissance. The first line
of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in
section 1.10.32.`
class App extends Component {
render() {
return (
<Box position="relative">
<Text>{str}</Text>
</Box>
)
}
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment