简体   繁体   中英

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.

The certText element is taken from a TinyMCE variable, where the user each time uses different HTML tags within the text.

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. I have read that with Canvas it's not possible to render the HTML tags, but is there any other alternative to succeed this. The code is used on a Laravel project that I have made.

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"?
Do you mean you want to style the text that is drawn on the canvas?
If so, you have to use canvas functions to set what the text will look like.
In the below example using your code, I use "fillStyle" to set the drawing fill colour in which the text will be drawn.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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