JS实现从照片中裁切自已的肖像
时间: 2024-03-15 07:46:37 浏览: 94
jquery实现头像剪切
要实现从照片中裁切自己的肖像,可以使用HTML5的Canvas API和JavaScript来完成。
首先,我们需要在HTML页面中添加一个canvas元素和一个图片元素用于显示照片:
```html
<!DOCTYPE html>
<html>
<head>
<title>Crop Portrait</title>
</head>
<body>
<img id="image" src="path/to/image.jpg">
<canvas id="canvas"></canvas>
</body>
</html>
```
然后,在JavaScript中获取canvas和图片元素,并将图片绘制到canvas上:
```javascript
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = document.getElementById('image');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
```
接下来,我们需要添加鼠标事件,使用户能够在canvas上选择要裁剪的区域:
```javascript
let isDragging = false;
let startX, startY, endX, endY;
canvas.addEventListener('mousedown', e => {
isDragging = true;
startX = e.offsetX;
startY = e.offsetY;
});
canvas.addEventListener('mousemove', e => {
if (!isDragging) return;
endX = e.offsetX;
endY = e.offsetY;
drawRect();
});
canvas.addEventListener('mouseup', e => {
isDragging = false;
endX = e.offsetX;
endY = e.offsetY;
drawRect();
});
function drawRect() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
ctx.strokeStyle = 'red';
ctx.strokeRect(startX, startY, endX - startX, endY - startY);
}
```
最后,我们需要添加一个按钮,当用户点击该按钮时,将裁剪的区域保存为图片,并显示在页面上:
```javascript
const cropBtn = document.createElement('button');
cropBtn.innerText = 'Crop';
document.body.appendChild(cropBtn);
cropBtn.addEventListener('click', () => {
const croppedImage = ctx.getImageData(startX, startY, endX - startX, endY - startY);
canvas.width = endX - startX;
canvas.height = endY - startY;
ctx.putImageData(croppedImage, 0, 0);
const croppedImageUrl = canvas.toDataURL();
const croppedImg = new Image();
croppedImg.src = croppedImageUrl;
document.body.appendChild(croppedImg);
});
```
现在,用户可以在canvas上选择要裁剪的区域,并将该区域保存为图片显示在页面上了。
阅读全文