-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeme.js
75 lines (61 loc) · 2.58 KB
/
meme.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
let topTextInput, bottomTextInput, topTextSizeInput, bottomTextSizeInput, imageInput, generateBtn, canvas, ctx;
function generateMeme (img, topText, bottomText, topTextSize, bottomTextSize) {
let fontSize;
// Size canvas to image
canvas.width = img.width;
canvas.height = img.height;
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw main image
ctx.drawImage(img, 0, 0);
// Text style: white with black borders
ctx.fillStyle = 'white';
ctx.strokeStyle = 'black';
ctx.textAlign = 'center';
// Top text font size
fontSize = canvas.width * topTextSize;
ctx.font = fontSize + 'px Impact';
ctx.lineWidth = fontSize / 20;
// Draw top text
ctx.textBaseline = 'top';
topText.split('\n').forEach(function (t, i) {
ctx.fillText(t, canvas.width / 2, i * fontSize, canvas.width);
ctx.strokeText(t, canvas.width / 2, i * fontSize, canvas.width);
});
// Bottom text font size
fontSize = canvas.width * bottomTextSize;
ctx.font = fontSize + 'px Impact';
ctx.lineWidth = fontSize / 20;
// Draw bottom text
ctx.textBaseline = 'bottom';
bottomText.split('\n').reverse().forEach(function (t, i) { // .reverse() because it's drawing the bottom text from the bottom up
ctx.fillText(t, canvas.width / 2, canvas.height - i * fontSize, canvas.width);
ctx.strokeText(t, canvas.width / 2, canvas.height - i * fontSize, canvas.width);
});
}
function init () {
// Initialize variables
topTextInput = document.getElementById('top-text');
bottomTextInput = document.getElementById('bottom-text');
topTextSizeInput = document.getElementById('top-text-size-input');
bottomTextSizeInput = document.getElementById('bottom-text-size-input');
imageInput = document.getElementById('image-input');
generateBtn = document.getElementById('generate-btn');
canvas = document.getElementById('meme-canvas');
ctx = canvas.getContext('2d');
canvas.width = canvas.height = 0;
// Default/Demo text
topTextInput.value = bottomTextInput.value = 'Demo\nText';
// Generate button click listener
generateBtn.addEventListener('click', function () {
// Read image as DataURL using the FileReader API
let reader = new FileReader();
reader.onload = function () {
let img = new Image;
img.src = reader.result;
generateMeme(img, topTextInput.value, bottomTextInput.value, topTextSizeInput.value, bottomTextSizeInput.value);
};
reader.readAsDataURL(imageInput.files[0]);
});
}
init();