Skip to content

Instantly share code, notes, and snippets.

@brainwipe
Last active May 27, 2022 00:03
Show Gist options
  • Save brainwipe/7689151 to your computer and use it in GitHub Desktop.
Save brainwipe/7689151 to your computer and use it in GitHub Desktop.
Using Snap.svg to create a box with text in it. The bounding "container" box expands to fit the width of the text.
<html>
<head>
<script src="//cdn.jsdelivr.net/snap.svg/0.1.0/snap.svg-min.js"></script>
<script>
var s = Snap("#svg");
var block = s.rect(50, 50, 100, 100, 20, 20);
block.attr({
fill: "rgb(236, 240, 241)",
stroke: "#1f2c39",
strokeWidth: 3
});
var text = s.text(70, 135, "Hello!");
text.attr({
'font-size':100
});
block.attr({
width: (text.node.clientWidth + 50)
});
</script>
</head>
<body>
<svg id="svg" version="1.1" xmlns="http://www.w3.org/2000/svg"></svg>
</body>
</html>
@brainwipe
Copy link
Author

Using Snap.svg http://www.snapsvg.io
More details on my blog: http://robsneuron.blogspot.co.uk

@MarekZeman91
Copy link

For some odd reason every measurable information is 0. Even with Snap.svg ...
Did this actually work for you?

@gallagherrchris
Copy link

I have found that in FireFox, text.node.clientWidth will always return 0. If you want to get the width, you need to use text.getBBox().width. This function noticeably slower than accessing the property that is available in Chrome.

@yosiasz
Copy link

yosiasz commented May 27, 2022

spent the whole day for var text = s.text(70, 135, "Hello!");
It was well worth it, I learned a whole bunch!

Thanks @brainwipe !!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment