我有一個背景圖像,我正在著色和下載的顏色,當我下載所有我看到的是顏色,因為背景圖像是透明的,它的模板由于某種原因沒有保存。 代碼如下:
const colorPicker = document.getElementById('colorPicker');
const fileInput = document.getElementById('fileInput');
const uploadedImage = document.getElementById('uploadedImage');
const tshirt = document.getElementById('tshirt');
const sizeRange = document.getElementById('sizeRange');
const saveButton = document.getElementById('saveButton');
// Update the t-shirt color on color change
colorPicker.addEventListener('change', function() {
tshirt.style.backgroundColor = colorPicker.value;
});
// Update the uploaded image
fileInput.addEventListener('change', function() {
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = function(e) {
uploadedImage.src = e.target.result;
};
reader.readAsDataURL(file);
});
// Save the background image with the file displayed on the shirt
saveButton.addEventListener('click', function() {
html2canvas(tshirt).then(function(canvas) {
const context = canvas.getContext('2d');
context.drawImage(uploadedImage, uploadedImage.offsetLeft, uploadedImage.offsetTop);
const combinedImageURL = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = combinedImageURL;
link.download = 'combined_image.png';
link.click();
});
});
/* CSS styling for the t-shirt */
#tshirt {
width: 450px;
height: 545px;
background-image: url('https://ourcodeworld.com/public-media/gallery/gallery-5d5afd3f1c7d6.png');
background-size: contain;
background-repeat: no-repeat;
position: relative;
margin: 50px auto;
text-align: center;
}
/* CSS styling for the color selection */
#colorPicker {
margin-top: 20px;
}
/* CSS styling for the file upload */
#fileInput {
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.0/html2canvas.min.js"></script>
<div id="tshirt">
<img id="uploadedImage" src="#" alt="Uploaded Image" class="draggable" style="max-width: 80%; max-height: 80%;" />
</div>
<input type="color" id="colorPicker" />
<input type="file" id="fileInput" />
<button id="saveButton">Save</button>