-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (66 loc) · 2.18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const imageFileInput = document.querySelector("#imageFileInput");
const canvas = document.querySelector("#meme");
const topTextInput = document.querySelector("#topTextInput");
const bottomTextInput = document.querySelector("#bottomTextInput");
const downloadBtnSection = document.querySelector(".button_section");
let image;
imageFileInput.addEventListener("change", (e) => {
const imageDataUrl = URL.createObjectURL(e.target.files[0]);
console.log(imageDataUrl);
image = new Image();
image.src = imageDataUrl;
image.addEventListener(
"load",
() => {
updateMemeCanvas(
canvas,
image,
topTextInput.value,
bottomTextInput.value
);
},
{ once: true }
);
});
topTextInput.addEventListener("keyup", () => {
updateMemeCanvas(canvas, image, topTextInput.value, bottomTextInput.value);
});
bottomTextInput.addEventListener("keyup", () => {
updateMemeCanvas(canvas, image, topTextInput.value, bottomTextInput.value);
console.log("Fill Up Bottom Text && You Have To Download Your Meme");
downloadBtnSection.style.display = "block";
});
function updateMemeCanvas(canvas, image, topText, bottomText) {
console.log(image);
const ctx = canvas.getContext("2d");
const width = image.width;
const height = image.height;
const fontSize = Math.floor(width / 10);
const yOffset = height / 25;
// Update canvas background
canvas.width = width;
canvas.height = height;
ctx.drawImage(image, 0, 0);
// Prepare text
ctx.strokeStyle = "black";
ctx.lineWidth = Math.floor(fontSize / 4);
ctx.fillStyle = "white";
ctx.textAlign = "center";
ctx.lineJoin = "round";
ctx.font = `${fontSize}px sans-serif`;
// Add top text
ctx.textBaseline = "top";
ctx.strokeText(topText, width / 2, yOffset);
ctx.fillText(topText, width / 2, yOffset);
// Add bottom text
ctx.textBaseline = "bottom";
ctx.strokeText(bottomText, width / 2, height - yOffset);
ctx.fillText(bottomText, width / 2, height - yOffset);
}
document.getElementById("export").onclick = function () {
var img = canvas.toDataURL("image/png");
var link = document.createElement("a");
link.download = "my_meme";
link.href = img;
link.click();
};