帮我写个html代码,能够实现图片的自由拼接,在上传图片后能够自由拖拽到指定位置进行拼接,而且图片的大小自适应画布的大小,图片总是能后在画布里全部显示,添加或者拖拽后,画布会自适应加大,而且有时候图片过大或者过小的情况可以实现图片大小的拉伸,能够下载拼接好的图片,代码写在一个框里
时间: 2024-06-05 14:06:26 浏览: 176
实现拼接图片
抱歉,我作为AI语言模型无法在此处提供代码编辑器。但我可以向您提供示例代码以供参考:
<!DOCTYPE html>
<html>
<head>
<title>图片自由拼接</title>
<style>
body {
margin: 0;
padding: 0;
}
#canvas {
border: 2px solid black;
background-color: white;
display: flex;
flex-wrap: wrap;
align-content: flex-start;
height: 500px;
width: 500px;
margin: 50px auto;
overflow: scroll;
}
.image {
position: relative;
margin: 10px;
cursor: move;
}
.image img {
max-width: 100%;
max-height: 100%;
display: block;
}
</style>
</head>
<body>
<h1>图片自由拼接</h1>
<div id="canvas"></div>
<input type="file" id="file-input">
<button id="download-btn">下载拼接图片</button>
<script>
const canvas = document.getElementById('canvas');
const fileInput = document.getElementById('file-input');
const downloadBtn = document.getElementById('download-btn');
let images = [];
// 上传图片
fileInput.addEventListener('change', function(e) {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = function() {
const image = new Image();
image.src = reader.result;
image.onload = function() {
const div = document.createElement('div');
div.classList.add('image');
div.appendChild(image);
canvas.appendChild(div);
images.push(div);
positionImages();
}
}
reader.readAsDataURL(file);
});
// 拖拽图片
let activeImage = null;
let initialX, initialY, currentX, currentY;
canvas.addEventListener('mousedown', function(e) {
if (e.target.classList.contains('image')) {
activeImage = e.target;
initialX = e.clientX - activeImage.offsetLeft;
initialY = e.clientY - activeImage.offsetTop;
activeImage.style.zIndex = 1;
}
});
canvas.addEventListener('mousemove', function(e) {
if (activeImage) {
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
activeImage.style.left = currentX + 'px';
activeImage.style.top = currentY + 'px';
}
});
canvas.addEventListener('mouseup', function(e) {
if (activeImage) {
activeImage.style.zIndex = 0;
activeImage = null;
}
});
// 调整图片大小
canvas.addEventListener('dblclick', function(e) {
if (e.target.tagName === 'IMG') {
e.target.style.maxWidth = 'none';
e.target.style.maxHeight = 'none';
}
});
// 重新定位图片
function positionImages() {
images.forEach(function(image) {
let x = Math.floor(Math.random() * (canvas.offsetWidth - image.offsetWidth));
let y = Math.floor(Math.random() * (canvas.offsetHeight - image.offsetHeight));
image.style.left = x + 'px';
image.style.top = y + 'px';
});
}
// 下载拼接好的图片
downloadBtn.addEventListener('click', function() {
const canvas2 = document.createElement('canvas');
canvas2.width = canvas.offsetWidth;
canvas2.height = canvas.offsetHeight;
const ctx = canvas2.getContext('2d');
html2canvas(canvas).then(function(canvas) {
const image = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.download = '拼接图片.png';
link.href = image;
link.click();
});
});
</script>
</body>
</html>
阅读全文