简体   繁体   English

HTML Canvas 内的文本

[英]HTML text inside Canvas

I need to render an image on which I have put some HTML text on it and then the user to be able to download the image with the text as an image or even better as a pdf.我需要渲染一个图像,我在上面放了一些 HTML 文本,然后用户能够下载带有文本作为图像的图像,甚至更好地下载为 pdf。

The certText element is taken from a TinyMCE variable, where the user each time uses different HTML tags within the text. certText 元素取自 TinyMCE 变量,其中用户每次在文本中使用不同的 HTML 标记。

So it could be所以它可能是

" Hello user, how are you" or " Hi there, great that you succeed on the certification ". 您好用户,您好吗”或“您好,很高兴您通过了认证”。

Starting from the image option I have created below code but Canvas do no translate the HTML tags.从我在下面的代码中创建的图像选项开始,但 Canvas 不翻译 HTML 标签。 I have read that with Canvas it's not possible to render the HTML tags, but is there any other alternative to succeed this.我已经阅读了 Canvas 无法呈现 HTML 标签,但是还有其他替代方法可以成功。 The code is used on a Laravel project that I have made.该代码用于我制作的 Laravel 项目。

var p = document.getElementById("certificate");
var ptx = p.getContext("2d");
var imgp = document.getElementById("certificateEmpty");
var txtp = document.getElementById("certText").innerHTML;
imgp.onload = function(){
ptx.drawImage(imgp, 0, 0);
ptx.font = "48px Nunito";
ptx.fillText(txtp, 150, 1000);
};
imgp.src = "{{$attendees[0]->certBLocation}}";

What are you trying to achive when you say "render html tags"?当你说“渲染 html 标签”时,你想达到什么目的?
Do you mean you want to style the text that is drawn on the canvas?您的意思是要设置在 canvas 上绘制的文本的样式吗?
If so, you have to use canvas functions to set what the text will look like.如果是这样,您必须使用 canvas 函数来设置文本的外观。
In the below example using your code, I use "fillStyle" to set the drawing fill colour in which the text will be drawn.在下面使用您的代码的示例中,我使用“fillStyle”来设置绘制文本的绘图填充颜色。

 var p = document.getElementById("certificate"); var ptx = p.getContext("2d"); var imgp = document.getElementById("certificateEmpty"); var txt = document.getElementById("certText"); var txtp = txt.innerHTML; imgp.onload = function(){ ptx.drawImage(imgp, 0, 0, p.width, p.height); var styles = window.getComputedStyle(txt); ptx.fillStyle = styles.color; //ptx.font = styles.font; // Doesn't seem to work in firefox. ptx.font = styles['font-weight']+" "+styles['font-size']+" "+styles.fontFamily; // Access properties array style because of hyphens. ptx.fillText(txtp, 0, 100); }; imgp.src = "https://www.gravatar.com/avatar/7b67c827ee1671ba3b43f4aebf6794fb?s=200";
 img, canvas { width: 200px; height: 200px; } #certText { color: #ff0000; font-weight: bold; font-size: 40px; }
 <img id="certificateEmpty"/> <canvas id="certificate"></canvas> <div id="certText"> some text </div>

Text drawn on the canvas looks squashed on my screen (Ubuntu/Chrome), not sure why. canvas 上绘制的文本在我的屏幕(Ubuntu/Chrome)上看起来被压扁,不知道为什么。

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

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