-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (45 loc) · 1.8 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
const imageFileInput = document.querySelector('#imageFileInput');
const topTextInput = document.querySelector('#topTextInput');
const bottomTextInput = document.querySelector('#bottomTextInput');
const canvas = document.querySelector('#meme');
let image;
imageFileInput.addEventListener('change', ()=>{
const imageDataUrl = URL.createObjectURL(imageFileInput.files[0]);
image = new Image();
image.src = imageDataUrl;
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 contxt = 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;
contxt.drawImage(image, 0, 0);
//prepare text
contxt.strokeStyle = 'black';
contxt.lineWidth = Math.floor(fontSize/4);
contxt.fillStyle = 'white';
contxt.textAlign = 'center';
contxt.lineJoin = 'round';
contxt.font = `${fontSize}px sans-serif`;
//add top text
contxt.textBaseline = 'top';
contxt.strokeText(topText, width/2, yOffset);
contxt.fillText(topText, width/2, yOffset);
//add bottom text
contxt.textBaseline = 'bottom';
contxt.strokeText(bottomText, width/2, height - yOffset);
contxt.fillText(bottomText, width/2, height - yOffset);
}