|
| 1 | +const fileInput = document.getElementById('fileinput'); |
| 2 | +const generateButton = document.querySelector('.generateBtn'); |
| 3 | + |
| 4 | + |
| 5 | +/*============ get image dimenstion ===============*/ |
| 6 | +generateButton.addEventListener('click', event => { |
| 7 | + if (fileInput.files.length > 0) { |
| 8 | + const img = document.createElement('img'); |
| 9 | + const selectedImage = fileInput.files[0]; |
| 10 | + const objectURL = URL.createObjectURL(selectedImage); |
| 11 | + |
| 12 | + img.onload = function handleLoad() { |
| 13 | + console.log(`Width: ${img.width}, Height: ${img.height}`); |
| 14 | + generateImage(img.height,img.width) |
| 15 | + URL.revokeObjectURL(objectURL); |
| 16 | + }; |
| 17 | + |
| 18 | + img.src = objectURL; |
| 19 | + } |
| 20 | + |
| 21 | + fileInput.value = null; |
| 22 | +}); |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | +/*================ generate placeholder image ===================*/ |
| 27 | +const imagePreview = document.getElementById("imagePreview"); |
| 28 | +const downloadImage = document.getElementById('download'); |
| 29 | + |
| 30 | +function generateImage(imageHeight,imageWidth) { |
| 31 | + const canvasElement = createPlaceholderCanvas( |
| 32 | + imageWidth, |
| 33 | + imageHeight |
| 34 | + ); |
| 35 | + const dataUrl = canvasElement.toDataURL(); |
| 36 | + |
| 37 | + downloadImage.href = dataUrl; |
| 38 | + imagePreview.src = dataUrl; |
| 39 | + imagePreview.style.display = "block"; |
| 40 | + imagePreview.style.maxWidth = `${imageWidth}px`; |
| 41 | + |
| 42 | + |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Creates a HTML canvas element of the given size. |
| 47 | + * |
| 48 | + * @param {number} width |
| 49 | + * @param {number} height |
| 50 | + * @returns {HTMLCanvasElement} |
| 51 | + */ |
| 52 | +function createPlaceholderCanvas(width, height) { |
| 53 | + const element = document.createElement("canvas"); |
| 54 | + const context = element.getContext("2d"); |
| 55 | + |
| 56 | + |
| 57 | + element.width = width; |
| 58 | + element.height = height; |
| 59 | + |
| 60 | + // Fill in the background |
| 61 | + context.fillStyle = "#aaaaaa"; |
| 62 | + context.fillRect(0, 0, element.width, element.height); |
| 63 | + |
| 64 | + // Place the text |
| 65 | + context.font = "bold 90px sans-serif"; |
| 66 | + context.fillStyle = "#333333"; |
| 67 | + context.textAlign = "center"; |
| 68 | + context.textBaseline = "middle"; |
| 69 | + context.fillText(`${width}x${height}`, element.width / 2, element.height / 2); |
| 70 | + |
| 71 | + return element; |
| 72 | +} |
| 73 | + |
0 commit comments