Created
March 31, 2020 09:56
-
-
Save pmanijak/69d1ba2142134799272112a09b9bd317 to your computer and use it in GitHub Desktop.
HTML and JavaScript client-side image overlay and download
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<!-- https://html2canvas.hertzen.com/ --> | |
<script src="html2canvas.min.js"></script> | |
<script> | |
function previewFile() { | |
const preview = document.querySelector('#client-image'); | |
const file = document.querySelector('input[type=file]').files[0]; | |
const reader = new FileReader(); | |
reader.addEventListener("load", function() { | |
// convert image file to base64 string | |
preview.src = reader.result; | |
}, false); | |
if (file) { | |
reader.readAsDataURL(file); | |
} | |
} | |
function download() { | |
html2canvas(document.querySelector('#preview')).then(function(canvas) { | |
var image = canvas.toDataURL("image/png"); | |
// Click a virtual anchor tag so we can name our download. | |
var anchor = document.createElement('a'); | |
anchor.setAttribute('download', 'profile-image.png'); | |
anchor.setAttribute('href', image); | |
anchor.click(); | |
}); | |
} | |
</script> | |
<style> | |
#client-image { | |
position: relative; | |
top: 0; | |
left: 0; | |
} | |
#overlay { | |
position: absolute; | |
top: 0; | |
left: 0; | |
} | |
#preview { | |
position: relative; | |
overflow: hidden; | |
width: 400px; | |
} | |
</style> | |
</head> | |
<body> | |
<input type="file" onchange="previewFile()"><br> | |
<div id="preview"> | |
<img id="client-image" src="" height="400" alt="Image preview..."> | |
<img id="overlay" src="overlay.png" height="400" width="400"/> | |
</div> | |
<button onclick="download()">Download</button> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment