How to get HTML5 canvas text to show html entity?

半腔热情 提交于 2019-12-10 16:24:08

问题


I'm parsing an xml file that stores image/caption data both of which I need to display on my canvas. However occasionally there's an entity in the file and when drawing the text to the canvas it interprets it as flat text. How can i get © to show up as © on the canvas? Is this even possible, or does anyone know of a good work around?


回答1:


You could replace the HTML entities with their equivalent unicode characters.

E.g.

var x = 'This is © 2010';
x = x.replace( /©/, '\u00A9' ); // x is now 'This is © 2010'



回答2:


Also Please note that all the HTML entities will be having the hex values

example for ℃ Hex value is "2103" we can convert it as "\u2103" and add it to canvas code

    <canvas id='my-canvas'></canvas>
    <script>
    var c = document.getElementById("my-canvas");  
    var ctx = c.getContext("2d");
    ctx.strokeText("170 \u2103", 25, 50);
    ctx.stroke();
    </script>



回答3:


Late, but for others searching for a solution:

var inputText = 'This is &copy; 2010';

var textContainer = document.createElement('span'); // Use a span to render the html entities
textContainer.innerHTML = inputText; // Set as innerhtml to make sure entities are converted

var outputText = textContainer.textContent; // x is now 'This is © 2010'

The input text is rendered just like normal text in html elements. This automatically converts all html entities.



来源:https://stackoverflow.com/questions/2653877/how-to-get-html5-canvas-text-to-show-html-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!