问题
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 © 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