Skip to content

Instantly share code, notes, and snippets.

@johnalarcon
Last active February 2, 2021 00:48
Show Gist options
  • Save johnalarcon/11303e962549427a02aca53dd3294390 to your computer and use it in GitHub Desktop.
Save johnalarcon/11303e962549427a02aca53dd3294390 to your computer and use it in GitHub Desktop.
Capture div as image and save to server with html2canvas
<?php
/**
* -----------------------------------------------------------------------------
* Capture div as image and save to server with html2canvas
* -----------------------------------------------------------------------------
* Copyright 2021, John Alarcon
* -----------------------------------------------------------------------------
* This is free software released under the terms of the General Public License,
* version 2, or later. It is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Full
* text of the license is available at https://www.gnu.org/licenses/gpl-2.0.txt.
* -----------------------------------------------------------------------------
*
* INSTRUCTIONS
*
* 1. Save this file to your local server.
* 2. Create an `images` directory in the same location as this file.
* 3. Visit this page in your browser; you will see a paragraph and a grid background.
* 4. Click the `Create Image` button.
* 5. Refresh your `images` directory – the image has been created.
*
* See: https://gist.github.com/johnalarcon/11303e962549427a02aca53dd3294390
*/
/**
* Direct URL to this file, ie: https://www.host.com/some-directory/index.php
*/
$redirect_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] = 'on') {
$redirect_url = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
/**
* This is a single-file proof of concept. It will both send an ajax request and
* receive an ajax request. This block handles the receiving end. It accepts the
* data, saves the image to the server, and redirects back to itself for another
* go.
*/
if (!empty($_POST['image'])) {
$string = str_replace('data:image/png;base64,', '', $_POST['image']);
file_put_contents('./images/'.time().'.png', base64_decode($string));
header('Location: '.$redirect_url);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Capture div as image and save to server with html2canvas</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.0.0-rc.7/dist/html2canvas.min.js"></script>
<script>
jQuery(document).ready(function($) {
var redirect_url = '<?php echo $redirect_url; ?>';
var ajax_file = '<?php echo basename($_SERVER['REQUEST_URI']); ?>';
$('button').click(function() {
var offScreen = document.querySelector('#content');
var clone = hiddenClone(offScreen);
html2canvas(clone, {
logging: false,
onrendered: function(clone) {
document.body.appendChild(canvas);
document.body.removeChild(clone);
}
}).then(function(clone) {
$.ajax({
method: 'POST',
url: ajax_file,
data: {
'image' : clone.toDataURL('image/png'),
},
}).done(function() {
alert('Image created');
window.location.replace(redirect_url);
}).fail(function() {
alert('Image failed');
window.location.replace(redirect_url);
});
});
});
function hiddenClone(element){
var clone = element.cloneNode(true);
var style = clone.style;
style.position = 'absolute';
style.top = 0;
style.left = 0;
style.width = $('#content').width();
document.body.appendChild(clone);
return clone;
}
});
</script>
<style>
html, body { margin:0; padding:0; }
#content { display:grid; max-width:100%; grid-template-columns:1fr; background:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAHYgAAB2IBOHqZ2wAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAAjSURBVBiVYzh9+nQDAxGAiRhFowoJAsbTp08fYGBgOEBIIQA3BQbUgAFEvQAAAABJRU5ErkJggg==') top left repeat #f2f2f2; }
#content p { margin:25px; padding:25px; border:1px solid #ccc; background:#fafafa; }
</style>
</head>
<body>
<div id="content"><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque ultricies magna mi, eget ultrices sem auctor non. Phasellus hendrerit ligula id ante fermentum accumsan. Sed fringilla cursus dui. Curabitur a turpis tortor. Nam tempus elit id enim laoreet, vel interdum lorem pulvinar. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis eu pharetra diam, quis feugiat orci.</p></div>
<p><button>Create Image</button></p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment