问题
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?
回答1:
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>
But given the complexity of the css gradients syntax, it's much harder to make something that will convert an already existing CSS background-image gradient into a canvas version. If someone wants to make this, I'd be glad to read it. So you will have to stick with hard-coded gradient values.
来源:https://stackoverflow.com/questions/34269494/how-to-save-canvas-for-gradient-background-php-html5