Patrick Lorio
Patrick Lorio

Reputation: 5668

javascript crop canvas to content

How can I go about cropping a HTML canvas around only it's content?

I am using strokeText to fill the canvas so it is difficult to compute the size of the content. Can I iterate over every pixel of the canvas, or is there something better?

Thanks

Upvotes: 0

Views: 433

Answers (2)

shabunc
shabunc

Reputation: 24831

Patrick, you can iterate through pixels in canvas, see "Pixel Manipulation" section in this awesome cheatsheet.

Of course, it is not an option - frankly, it would be just insane - to perform per-pixel analysis just to do something with text. So here comes measureText mentioned by @RobotRock. It worth to mention, though, that, to my experience, measureText is not 100% reliable in some cases.

It is also worth to mention text manipulation properties from API: textAlign and textBaseline. Because there is >50% probability that if you asking about measureText, you actually want to align text somehow )))

Upvotes: 1

RobotRock
RobotRock

Reputation: 4459

Use measureText in advance to check how much space is taken by the text. I hope that answers your question.

Upvotes: 1

Related Questions