This is code where user select one image.
This image is succesfully overlayed by second image and the result is image3.png. But image3 is not possible to download by button. I am not also able to download image by mouse click. There is not "image3.png" in inspect. Do you see any error why?
<!DOCTYPE html>
<html lang="cs">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New image</title>
</head>
<body>
<input type="file" id="backgroundImageInput" accept="image/*">
<canvas id="canvas" width="400" height="300"></canvas>
<button id="downloadBtn" style="display: none;">Stáhnout image3</button>
<script>
function drawOverlayedImage(backgroundImage, overlayImage) {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = backgroundImage.width;
canvas.height = backgroundImage.height;
ctx.drawImage(backgroundImage, 0, 0);
ctx.drawImage(overlayImage, 0, 0);
document.getElementById('downloadBtn').style.display = 'block';
}
function downloadImage() {
const canvas = document.getElementById('canvas');
const image = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.download = finalimage;
link.href = image;
link.click();
}
document.getElementById('backgroundImageInput').addEventListener('change', function(event) {
const backgroundImageFile = event.target.files[0];
if (backgroundImageFile) {
const reader = new FileReader();
reader.onload = function(e) {
const backgroundImage = new Image();
backgroundImage.src = e.target.result;
const overlayImage = new Image();
overlayImage.src = 'image2.png';
overlayImage.onload = function() {
const finalimage = drawOverlayedImage(backgroundImage, overlayImage);
};
}
reader.readAsDataURL(backgroundImageFile);
}
});
document.getElementById('downloadBtn').addEventListener('click', downloadImage);
</script>
</body>
</html>
finalimage
is undefined indownloadImage
andfinalimage
is scoped only to the listener ofoverlayImage.onload
and when declared is assignedundefined
by the return of functiondrawOverlayedImage
. First line of the script add the line"use strict";
to find all the errors your code has.