
How to Remove Image Background Using Clipdrop API in JavaScript
Features of Our Background Remover
- Drag-and-Drop & File Upload: Users can drag and drop an image or choose one from their device.
- Image Preview: The uploaded image is displayed before processing.
- Remove Background: Calls the Clipdrop API to remove the image background.
- Download Processed Image: Automatically downloads the background-removed image.
1. Setting Up the HTML Structure
We will create a simple UI with a drag-and-drop area, an image preview section, and a button to remove the background.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Remove Background</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Remove Background</h1>
<div id="dropArea" class="drop-area">
<p>Drag & Drop an Image or <span>Click to Browse</span></p>
<input type="file" id="fileInput" accept="image/*" hidden>
</div>
<div id="previewContainer" class="preview-container">
<img id="previewImage" src="#" alt="Image Preview" style="display: none;">
</div>
<button id="removeBgButton" disabled>Remove Background</button>
</div>
<script src="script.js"></script>
</body>
</html>
2. Styling the UI with CSS
To make our UI visually appealing, we use the following CSS styles:
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
text-align: center;
background: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
width: 90%;
max-width: 500px;
}
.drop-area {
border: 2px dashed #ccc;
border-radius: 10px;
padding: 20px;
cursor: pointer;
background-color: #fafafa;
margin-bottom: 20px;
}
.drop-area p {
margin: 0;
font-size: 16px;
color: #666;
}
.drop-area span {
color: #007BFF;
text-decoration: underline;
cursor: pointer;
}
.preview-container {
margin: 20px 0;
display: flex;
justify-content: center;
}
.preview-container img {
max-width: 100%;
max-height: 300px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
padding: 10px 20px;
font-size: 16px;
color: #fff;
background-color: #007BFF;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
button:hover:enabled {
background-color: #0056b3;
}
3. Writing the JavaScript Functionality
Now, we implement the drag-and-drop, preview, and background removal logic using JavaScript.
3.1 Handling File Uploads and Drag-and-Drop
The following code allows users to select an image by either clicking to browse or dragging and dropping it into the designated area.
const dropArea = document.getElementById('dropArea');
const fileInput = document.getElementById('fileInput');
const previewImage = document.getElementById('previewImage');
const previewContainer = document.getElementById('previewContainer');
const removeBgButton = document.getElementById('removeBgButton');
let selectedFile = null;
// Drag-and-Drop Events
dropArea.addEventListener('dragover', (e) => {
e.preventDefault();
dropArea.classList.add('active');
});
dropArea.addEventListener('dragleave', () => {
dropArea.classList.remove('active');
});
dropArea.addEventListener('drop', (e) => {
e.preventDefault();
dropArea.classList.remove('active');
const file = e.dataTransfer.files[0];
handleFile(file);
});
// File Input Click
dropArea.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
handleFile(file);
});
3.2 Previewing the Selected Image
Once an image is selected, we use the FileReader API to display the image preview.
function handleFile(file) {
if (file && file.type.startsWith('image/')) {
selectedFile = file;
const reader = new FileReader();
reader.onload = (e) => {
previewImage.src = e.target.result;
previewImage.style.display = 'block';
removeBgButton.disabled = false;
};
reader.readAsDataURL(file);
} else {
alert('Please upload a valid image file.');
}
}
3.3 Removing the Background with Clipdrop API
This function sends the image to Clipdrop API and replaces the preview with the processed image.
// Remove Background
removeBgButton.addEventListener('click', async () => {
const myHeaders = new Headers();
myHeaders.append("x-api-key", "YOUR_CLIPDROP_API_KEY");
const formdata = new FormData();
formdata.append("image_file", selectedFile);
const requestOptions = {
method: "POST",
headers: myHeaders,
body: formdata,
redirect: "follow"
};
fetch("https://clipdrop-api.co/remove-background/v1", requestOptions)
.then((response) => response.blob())
.then((blob) => {
const url = URL.createObjectURL(blob);
// Update Preview
previewImage.src = url;
// Auto-download the file
const a = document.createElement('a');
a.href = url;
a.download = 'output.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
removeBgButton.textContent = 'Remove Background';
removeBgButton.disabled = false;
})
.catch((error) => {
console.error('Error:', error);
alert('Failed to remove background.');
removeBgButton.textContent = 'Remove Background';
removeBgButton.disabled = false;
});
});
Conclusion
By following this tutorial, you have successfully created a JavaScript-based image background remover using the Clipdrop API. This feature can be integrated into various web applications, such as online editors, profile image processors, or e-commerce platforms. Happy coding!