h5手机实现拍照取景框
实现拍照取景框的方法
在H5手机端实现拍照取景框,可以通过HTML5的<input type="file">结合Canvas绘制取景框来实现。以下是一种常见的实现方式:
HTML部分

<input type="file" id="cameraInput" accept="image/*" capture="camera">
<canvas id="previewCanvas"></canvas>
CSS部分
#previewCanvas {
width: 100%;
height: auto;
border: 1px solid #ccc;
}
JavaScript部分

const cameraInput = document.getElementById('cameraInput');
const previewCanvas = document.getElementById('previewCanvas');
const ctx = previewCanvas.getContext('2d');
cameraInput.addEventListener('change', function(e) {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
// 设置canvas尺寸与图片一致
previewCanvas.width = img.width;
previewCanvas.height = img.height;
// 绘制图片
ctx.drawImage(img, 0, 0, img.width, img.height);
// 绘制取景框(示例为中央正方形)
const size = Math.min(img.width, img.height) * 0.7;
const x = (img.width - size) / 2;
const y = (img.height - size) / 2;
ctx.strokeStyle = '#FF0000';
ctx.lineWidth = 5;
ctx.strokeRect(x, y, size, size);
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
}
});
使用MediaDevices API实现实时取景
对于更高级的实时取景框效果,可以使用MediaDevices API:
navigator.mediaDevices.getUserMedia({ video: true })
.then(function(stream) {
const video = document.createElement('video');
video.srcObject = stream;
video.play();
const drawFrame = function() {
if (video.readyState === video.HAVE_ENOUGH_DATA) {
// 绘制视频帧
ctx.drawImage(video, 0, 0, previewCanvas.width, previewCanvas.height);
// 绘制取景框
const size = Math.min(previewCanvas.width, previewCanvas.height) * 0.7;
const x = (previewCanvas.width - size) / 2;
const y = (previewCanvas.height - size) / 2;
ctx.strokeStyle = '#FF0000';
ctx.lineWidth = 5;
ctx.strokeRect(x, y, size, size);
}
requestAnimationFrame(drawFrame);
};
drawFrame();
})
.catch(function(err) {
console.error('Error accessing camera: ', err);
});
注意事项
- 移动端浏览器对相机API的支持程度不同,需要进行特性检测
- 部分浏览器可能需要HTTPS环境才能访问相机
- 取景框的样式可以根据需求自定义,如圆形、矩形或其他形状
- 考虑添加拍照按钮和照片处理功能
兼容性处理
对于不支持MediaDevices API的浏览器,可以回退到文件输入方式:
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
cameraInput.style.display = 'block';
} else {
// 使用MediaDevices API
}
以上方法提供了在H5手机端实现拍照取景框的基本思路,可以根据具体需求进行调整和扩展。





