Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to saving gradient linear background. I am using a plugin of https://github.com/niklasvh/html2canvas/releases.

The code is working for solid background color and images but not when I use css background-linear-gradient.

and how can i save this canvas image?

//EDITED:

I have another bug

I would like to save data which is loading from database, so i am looping between the database and showing content. How can i save the pictures one by one showing the content?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
332 views
Welcome To Ask or Share your Answers For Others

1 Answer

In the browser-compatibility section of the html2canvas' readme you can read :

As each CSS property needs to be manually built to be supported, there are a number of properties that are not yet supported.

background-image 's gradients are of those.

You will just have to write it yourself or wait until someone does for the html2canvas library.

If you've got a fixed gradient to render, it's quite easy to render it on a canvas element first, and set the dataURI version of this canvas to the background-image of your css.

var renderGradients = function(elem){
  // get the size of your element
  var rect = elem.getBoundingClientRect();
  // create a canvas and set it to the same size as the element
  var canvas = document.createElement('canvas');
  canvas.width = rect.width;
  canvas.height = rect.height;
  
  var ctx = canvas.getContext('2d');
  // create a new gradient, the size of our element
  var gradient = ctx.createLinearGradient(0,0,rect.width,rect.height);
  // add the colors we have in our style
  gradient.addColorStop(0, 'blue');
  gradient.addColorStop(1, 'red');
  
  ctx.fillStyle = gradient;
  // draw a rect with our gradient
  ctx.fillRect(0, 0, rect.width, rect.height);
  // set our element's background-image to the canvas computed gradient
  elem.style.backgroundImage = 'url('+canvas.toDataURL()+')';

  // now call html2canvas
  html2canvas(elem, {onrendered : function(can){
      document.body.appendChild(can);
    }});
  }

renderGradients(cont);
#cont {background-image: linear-gradient( 90deg, blue, red );}
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<div id="cont">
  Some content
</div>
html2canvas result : <br>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...