Welcome folks today in this blog post we will be using the canvas api
in javascript to draw different shapes
and hide the faces
inside the image file in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
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 77 78 79 80 81 82 83 84 85 86 87 88 |
<!DOCTYPE html> <html> <head> <title>Image Editor</title> <style> #canvas { border: 1px solid black; } </style> </head> <body> <input type="file" id="image-selector" accept="image/*" /> <br /> <button id="circle-button">Draw Circle</button> <button id="clear">Clear</button> <input type="color" value="#ffffff" id="color-picker" /> <br /> <canvas id="canvas"></canvas> <br /> <a id="download-link" download="modified-image.png" href="#">Download Modified Image</a> <script> const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const imageSelector = document.getElementById('image-selector'); const circleButton = document.getElementById('circle-button'); const colorPicker = document.getElementById('color-picker'); const downloadLink = document.getElementById('download-link'); const clearBtn = document.getElementById('clear') let image = null; let shapes = []; // Load image when user selects one imageSelector.addEventListener('change', () => { const fileReader = new FileReader(); fileReader.onload = () => { const img = new Image(); img.onload = () => { canvas.width = img.width; canvas.height = img.height; context.drawImage(img, 0, 0); image = context.getImageData(0, 0, canvas.width, canvas.height); }; img.src = fileReader.result; }; fileReader.readAsDataURL(imageSelector.files[0]); }); clearBtn.addEventListener('click',(e) => { shapes = [] drawShapes() }) // Draw circle when user clicks circle button circleButton.addEventListener('click', () => { canvas.addEventListener('click', (event) => { const x = event.offsetX; const y = event.offsetY; const radius = 50; const color = colorPicker.value; const shape = { type: 'circle', x, y, radius, color }; shapes.push(shape); drawShapes(); }); }); // Draw all shapes on canvas function drawShapes() { context.clearRect(0, 0, canvas.width, canvas.height); context.putImageData(image, 0, 0); shapes.forEach((shape) => { context.beginPath(); if (shape.type === 'circle') { context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); } context.fillStyle = shape.color; context.fill(); }); } // Download modified image when user clicks download link downloadLink.addEventListener('click', () => { const dataUrl = canvas.toDataURL(); downloadLink.href = dataUrl downloadLink.click(); }); </script> |