How to make transparent color white instead of bla

2019-01-14 22:26发布

问题:

I'm trying to take a screenshot using html2canvas:

var body = document.getElementById("body")
$(body).html2canvas({onrendered: function( canvas ) {  
     var urlData = canvas.toDataURL("image/jpeg");  
}});

My body's background is transparent, and therefore urlData because of jpeg has black background (not white like in browser).
How can I fix this behavior and make background color white in this case?

回答1:

I modified temporary: _html2canvas.Util.isTransparent from

_html2canvas.Util.isTransparent = function(backgroundColor) {
  return (backgroundColor === "transparent" || backgroundColor === "rgba(0, 0, 0, 0)");
};

to

_html2canvas.Util.isTransparent = function(backgroundColor) { return (backgroundColor === "transparent" || backgroundColor === "rgba(0, 0, 0, 0)" || backgroundColor === undefined); };

and after that it was enough to call html2canvas with background parameter set:

html2canvas(screenshot_element, {
    background :'#FFFFFF',
    onrendered: function (canvas) {
      .....
    }
  });

For me... it makes sense to consider transparent a background that is undefined.



回答2:

Try this

var body = document.getElementById("body") 
$(body).html2canvas({background:'#fff', onrendered: function( canvas ) {  
 var urlData = canvas.toDataURL("image/jpeg");  
}});


回答3:

https://stackoverflow.com/a/23928038/1815624

simply add css background-color:#ffffff to your table :)

hope this helps

I wrapped the content into a div for each desired page and gave class="pdfpage" then set the css as pdfpage{background:#FFFFFF;}

As I had commented it was not first thoughts that I needed to set the background of the rendered element as white since it was white already...But in truth it was colorless...



回答4:

var body = document.getElementById("body")
$(body).html2canvas({onrendered: function( canvas ) {  
     var urlData = canvas.toDataURL("image/jpeg");  
},
background: '#fff'});

Two years later but updated version should accept a parameter like this . . .



回答5:

I'd say, it's even simplier now(30/05/18) - just pass backgroundColor: null in html2canvas options:

html2canvas(
    document.querySelector("#some-id-to-export"),
    {backgroundColor: null}
).then(canvas => {$("#id-to-render-transparent-bg-img").html(canvas);});


回答6:

No worries, Now just add background: '#FFFFFF' , its working fine

                   html2canvas(element, {
                       background: '#FFFFFF',
                       onrendered: function (canvas) {
                           $("#previewImage").append(canvas);
                           getCanvas = canvas;
                       }
                   });


标签: html2canvas