There is no way to take a real screen-shot of any element through canvas. (at least not in WebAPI, in some browsers, extensions are allowed to do so).
You will have to create a new Image
object, set it's src to the one of the background-image, and then only be able to draw it on the canvas.
But if the server answers with a no-cache
, then the Image
will just load an other image than the one set as background.
So you will have to make things in the other way :
- First load the image through an
Image
Object.
- Then draw this image to a canvas and get its dataURI version by calling
canvas.toDataURL()
.
- Finally, set your element's background to this dataURI you just extracted.
// first load your image from the server once, into an Image object
var img = new Image();
// wait for the image has loaded
img.onload = function(){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage(this, 0,0);
// since I'm receiving photos, jpeg is better
var dataURL = canvas.toDataURL('image/jpeg');
// if we could use local storage in snippets...
//localStorage.setItem('background-image', dataURL);
// since we can't
saved = dataURL;
document.body.style.backgroundImage = 'url('+dataURL+')';
}
// I'm loading it from an external server
img.crossOrigin = 'anonymous';
img.src = 'http://lorempixel.com/200/200/?'+Math.random();
// since we can't use local storage in sand-boxed iframe
// we will use a global in this snippet
var saved;
button.onclick = function(){
// if we could use localStorage
// var saved = localStorage.getItem('background-image');
document.getElementById('result').style.backgroundImage = 'url('+saved+')';
};
div{width: 200px; height: 200px; border: 1px solid; background-color: white;}
body{width: 100vw; height: 100vh; margin: 0;}
<button id="button">set the div's background to the saved one</button>
<div id="result"></div>
Note that localStorage
is limited so depending on your graphics, you may want to use the image/jpeg
compression type of the toDataURL()
method.
Also, you'll be limited by cross-origin policies, if the php page is not on the same domain, make sure it is correctly configured to accept cross-origin requests and set you Image
object's crossOrigin
property to "anonymous"
.
Ps : You could also avoid the canvas part by using an XMLHttpRequest
and a FileReader()
, wich will involve different cross-origin restrictions.