Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTMLMesh: added textNode wrapping #24781

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 70 additions & 1 deletion examples/jsm/interactive/HTMLMesh.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,43 @@ function html2canvas( element ) {

}

function getLines( element, text, maxWidth ) {

const words = text.split( " " );
const lines = [];
let currentLine = words[ 0 ];

for ( let i = 1; i < words.length; i ++ ) {

// Somehow, the textnode width in pixels differs from the parent element width.
// Using the range instead of the context to compute the wrapping width fixes this problem.

const word = words[ i ];
range.setStart( element, 0 );

const newLine = currentLine + " " + word;
range.setEnd( element, newLine.length );

const width = range.getBoundingClientRect().width;

if ( width < maxWidth ) {

currentLine = newLine;

} else {

lines.push( currentLine );
currentLine = word;

}

}

lines.push( currentLine );
return lines;

}

function buildRectPath( x, y, w, h, r ) {

if ( w < 2 * r ) r = w / 2;
Expand Down Expand Up @@ -254,7 +291,39 @@ function html2canvas( element ) {
width = rect.width;
height = rect.height;

drawText( style, x, y, element.nodeValue.trim() );
const text = element.nodeValue.trim();


if ( element.parentElement ) {

const parentEl = element.parentElement;
const parentWidth = parentEl.offsetWidth;

//set to nowrap so that range doesn't warp in the getLines function
const whiteSpaceValue = parentEl.style.whiteSpace;
parentEl.style.whiteSpace = "nowrap";

const lineHeight = range.getBoundingClientRect().height;
const lines = getLines( element, text, parentWidth );

parentEl.style.whiteSpace = whiteSpaceValue;


range.selectNode( element );

for ( const line of lines ) {

drawText( style, x, y, line );

y += lineHeight;

}

} else {

drawText( style, x, y, text );

}

} else if ( element.nodeType === Node.COMMENT_NODE ) {

Expand Down