Aaron Newman Aaron Newman - 1 year ago 256
HTML Question

Html to canvas background color wraps incorrectly

I am using html2canvas.js 0.4.1 to convert a DOM to canvas for printing. When the text has a background color on a span, and the span wraps to the next line, then the canvas version covers the whole rectangle of the 2 wrapping lines. It doesn't just cover the text. Furthermore it hides the text in the prior span.

The following fiddle demonstrates it pretty well. The 'one one' span is completely covered up by the blue background on the 'two two' span.



#content {
.select {


<div id='content'>
<span >one one one one one one </span>
<span class="select" >two two two two two two </span>
<span >three three three three three </span>

<div id="img-out"></div>


html2canvas($("#content"), {
onrendered: function(canvas) {
theCanvas = canvas;

// Convert and download as image
// Clean up

My theory is html2canvas can't tell what the bounding box of the spans are, or maybe it just doesn't support multiple rectangles as bounds.

Is there any type of CSS effect I can use on the HTML text that will render correctly in html2canvas? It doesn't have to be a background color, but I have to somehow indicate that the wrapping span is highlighted.

Answer Source

Canvas does not support multi line inline texts. So your libraries splits it up, but the wrapping .select box gets the dimensions like an inline-block element.

You need to split and wrap every highlighted word with a seperate span.


var $selected = $('#content.notupdated .select');
$selected.each( function() {
    var $this = $(this);
    var words = $this.text().split(" ");
    $.each(words, function(i, v) {
        $this.append($("<span>").text(v + ' '));

I updated you fiddle for that: https://jsfiddle.net/sddah9k2/7/
I even updated @Kaiidos improved fiddle of yours: https://jsfiddle.net/sddah9k2/6/ (I worked primarily on that one)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download