Skip to content

Instantly share code, notes, and snippets.

@MaverickTse
Created August 16, 2017 01:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaverickTse/bfec6768c2e7a3c46c25b61eb2d00d97 to your computer and use it in GitHub Desktop.
Save MaverickTse/bfec6768c2e7a3c46c25b61eb2d00d97 to your computer and use it in GitHub Desktop.
Estimate rendered length of a string in SVG and HTML5 canvas
<!DOCTYPE HTML>
<html>
<head>
<meta lang="en-us" encoding="utf-8"/>
<title>Canvas Test</title>
<script>
function check_txt_length()
{
var txt = document.getElementById("sample").value;
var cv = document.createElement("canvas");
var ctx = cv.getContext("2d");
ctx.font = "16px Arial";
console.log("testing");
console.log(ctx.measureText(txt).width);
cv.remove();
}
function svg_estimate()
{
var txt = document.getElementById("sample").value;
var svgns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(svgns, "svg");
var gnode = document.createElementNS(svgns, "g");
var tnode = document.createElementNS(svgns, "text");
var tmsg = document.createTextNode(txt);
tnode.setAttribute("font-size", 18);
tnode.setAttribute("font-family", "Arial");
tnode.setAttribute("x", 50);
tnode.setAttribute("y", 50);
tnode.appendChild(tmsg);
gnode.appendChild(tnode);
svg.appendChild(gnode);
document.body.appendChild(svg);
var len_est = tnode.getComputedTextLength();
console.log(len_est);
svg.remove();
}
</script>
</head>
<body>
<p id="page">
<input type="text" id="sample"></input>
<button onclick="check_txt_length()">Canvas Estimate</button>
<button onclick="svg_estimate()">SVG Estimate</button>
</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment