简体   繁体   English

在html5画布中将文本绘制为图像

[英]Draw Text as image in html5 canvas

I am working in a HTML5 project.I want to draw text with boundaries (ie. Text Annotation). 我正在HTML5项目中工作。我想绘制带边界的文本(即文本注释)。

First i am drawing an rectangle and filling text inside it on mousemove as follow: 首先,我在mousemove上绘制一个矩形并在其中填充文本,如下所示:

context.strokeRect(x,y,w,h);
context.fillText('Enter youe text here',x,y);

but when i start to draw text annotation, then text draw completely. 但是当我开始绘制文本注释时,则文本完全绘制。 so text overflow outside the rectangle boundary. 所以文本溢出矩形边界。 So i want to take image of rectangle part then i can manage this overflow problem of text. 所以我想拍摄矩形部分的图像,然后我可以管理文本的溢出问题。 I am using following way to do this:- 我使用以下方式执行此操作: -

 context.strokeRect(x,y,w,h);
 context.fillText('Enter youe text here',x,y);
 var imageData = context.getImageData(x,y,w,h);
 var data = imageData.data;
 context.putImageData(imageData, x,y);

Through this way text-image is creating at successfully,but now how can i hide the fillText(x,y,w,h) statement and i am also taking image-data imside rectangle with help of the text. 通过这种方式文本图像成功创建,但现在我如何隐藏fillText(x,y,w,h)语句,我也在文本的帮助下采取图像数据imside矩形。

THanks a lot in advance 提前收了很多

It seems as you want to measure the text width and split the canvas up, if I am understanding correctly? 如果我正确理解的话,您似乎想要测量文本宽度并将画布分开?

I prototyped a little example that explains how to use the measureText method: 我原型了一个小例子,解释了如何使用measureText方法:

http://jsfiddle.net/sQ3S7/ http://jsfiddle.net/sQ3S7/

Actually, as you can see in the demo, it returns no measured height dimension. 实际上,正如您在演示中所看到的,它不返回测量的高度尺寸。 So you may have to loop through the canvas line-by-line to find out how the height of the text is. 因此,您可能需要逐行遍历画布以了解文本的高度。

For my JS game engine, I did a little font tool that does exactly that and exports it to a JSON format, maybe the algorithms behind will help you on your way :) 对于我的JS游戏引擎,我做了一个小字体工具来完成它并将其导出为JSON格式,也许后面的算法将帮助你的方式:)

http://martens.ms/lycheeJS/tool/Font.html http://martens.ms/lycheeJS/tool/Font.html

Code is available on github.com/martensms/lycheeJS (Can't post more than two links as I'm new to SO) 代码可以在github.com/martensms/lycheeJS上找到(因为我是SO的新手,所以不能发布两个以上的链接)

~Cheers 〜干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM