-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
76 lines (63 loc) · 2.75 KB
/
script.js
File metadata and controls
76 lines (63 loc) · 2.75 KB
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
let topTextInput,
bottomTextInput,
topTextSizeInput,
bottomTextSizeInput,
imageInput,
generateBtn,
canvas,
ctx;
function generateMeme(img, topText, bottomText, toptextSize, bottomtextSize) {
canvas.width = img.width; // set canvas width to image width
canvas.height = img.height; // set canvas height to image height
ctx.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
ctx.drawImage(img, 0, 0); // draw the image starting from 0,0 of canvas
// DRAW THE TEXTS
ctx.fillStyle = 'white';
ctx.strokeStyle = 'black';
ctx.textAlign = 'center';
// toptext size
fontSize = canvas.width * toptextSize;
ctx.font = fontSize + 'px Impact';
ctx.lineWidth = fontSize / 15;
// draw the 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)
})
// bottomtext size
fontSize = canvas.width * bottomtextSize;
ctx.font = fontSize + 'px Impact';
ctx.lineWidth = fontSize / 15;
// draw the bottom text
ctx.textBaseline = 'bottom';
bottomText.split('\n').reverse().forEach(function(t, i) {
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() {
// grab the HTML tags
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'); // specify whether canvas is 2D or 3D
canvas.width = canvas.height = 0; // set canvas height and width to zero so that it disappear when there is no image
// click handler
generateBtn.addEventListener('click', function() {
let reader = new FileReader(); // use the file reader API to read file of the user's computer
reader.onload = function() {
let img = new Image; // make a new image with Image object
img.src = reader.result; // choose image source with src method
generateMeme(img, topTextInput.value, bottomTextInput.value, topTextSizeInput.value, bottomTextSizeInput.value); // the last two parameters get the values of the arguments
};
reader.readAsDataURL(imageInput.files[0]); // select image to draw on canvas
})
}
init();