Created
August 16, 2017 01:55
-
-
Save MaverickTse/bfec6768c2e7a3c46c25b61eb2d00d97 to your computer and use it in GitHub Desktop.
Estimate rendered length of a string in SVG and HTML5 canvas
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
<!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