meme
unknown
javascript
3 years ago
1.7 kB
5
Indexable
const imageFileInput = document.querySelector("#imageFileInput");
const canvas = document.querySelector("#meme");
const topTextInput = document.querySelector("#topTextInput");
const bottomTextInput = document.querySelector("#bottomTextInput");
let image;
imageFileInput.addEventListener("change", (e) => {
const imageDataUrl = URL.createObjectURL(e.target.files[0]);
image = new Image();
image.src = '01.jpg';
image.addEventListener(
"load",
() => {
updateMemeCanvas(
canvas,
image,
topTextInput.value,
bottomTextInput.value
);
},
{ once: true }
);
});
topTextInput.addEventListener("change", () => {
updateMemeCanvas(canvas, image, topTextInput.value, bottomTextInput.value);
});
bottomTextInput.addEventListener("change", () => {
updateMemeCanvas(canvas, image, topTextInput.value, bottomTextInput.value);
});
function updateMemeCanvas(canvas, image, topText, bottomText) {
const ctx = canvas.getContext("2d");
const width = image.width;
const height = image.height;
const fontSize = Math.floor(width / 25);
const yOffset = height / 4;
// Update canvas background
canvas.width = width;
canvas.height = height;
ctx.drawImage(image, 0, 0);
// Prepare text
ctx.fillStyle = "black";
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);
}Editor is loading...