I need your help :)
So I followed a tutorial about making a duotone with canvas. It takes an image, convert it into grayscale and then to duotone. Now I'm trying to download the canvas as a PNG, but it downloads an empty image.
"It looks like your post is mostly code; please add some more details." No quite sure how I can ad more details :(
Any idea how to fix?
I'm kinda newbie. Thx in advance
<html>
<head> </head>
<body>
<div id="main">
<canvas id="duotone" width="600" height="600"></canvas>
</div>
<script>
function Duotone(id, src, primaryClr, secondaryClr, actions = (ctx) => null) {
let canvas = document.getElementById(id);
let ctx = canvas.getContext("2d");
let downloadedImg = new Image();
downloadedImg.crossOrigin = "";
downloadedImg.onload = function() {
ctx.drawImage(downloadedImg, 0, 0, canvas.width, canvas.height);
imageData = ctx.getImageData(0, 0, 800, 800);
const pixels = imageData.data;
for (let i = 0; i < pixels.length; i += 4) {
const red = pixels[i];
const green = pixels[i + 1];
const blue = pixels[i + 2];
const avg = Math.round((0.299 * red + 0.587 * green + 0.114 * blue) * 1);
pixels[i] = avg;
pixels[i + 1] = avg;
pixels[i + 2] = avg;
}
ctx.putImageData(imageData, 0, 0);
ctx.globalCompositeOperation = "multiply";
ctx.fillStyle = primaryClr;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = "lighten";
ctx.fillStyle = secondaryClr;
ctx.fillRect(0, 0, canvas.width, canvas.height);
};
downloadedImg.src = src;
}
function randomIndex() {
return Math.floor(Math.random() * 3);
}
function randomizeColors() {
// Arrays of colors, with a random index chosen when clicked.
let primary = ["#f65e35", "#00ff36", "#77acd4"];
let secondary = ["#1e3265", "#23278a", "#033dc5"];
let ind = randomIndex();
Duotone(
"duotone",
"https://i.imgur.com/WQ1Iydl.jpeg",
primary[ind],
secondary[ind],
);
}
function downloadImage() {
document.querySelector("#image").src = document
.querySelector("#duotone")
.toDataURL("image/png");
}
var canvas = document.getElementById("duotone");
var image = canvas.toDataURL();
var aDownloadLink = document.createElement('a');
aDownloadLink.download = 'canvas_image.png';
aDownloadLink.href = image;
aDownloadLink.click();
randomizeColors();
</script>
</body>
</html>
What you're trying to download isn't ready yet, you have to wait for it to be fully loaded.
window.onload = function () {
var canvas = document.getElementById("duotone");
var image = canvas.toDataURL();
var aDownloadLink = document.createElement("a");
aDownloadLink.download = "canvas_image.png";
aDownloadLink.href = image;
aDownloadLink.click();
};