我有一个使用JavaScript和HTML画布的网页。用户可以使用网络摄像头拍照的地方。摄像机前面的框架在哪里,该框架指示应将用户的头部放置在何处。该框架可调整大小且可移动。我想建立一个系统,让用户拍摄一张照片,将其头部和身体放在框架中,并可以固定大小下载该照片。我的代码正在做同样的事情,只有一个问题是,如果我不调整框架的大小,那么它将给出确切所需大小的输出图片,但是如果我调整框架的大小,则图像大小将变得更大或更小。但是无论帧大小有多大,我都希望以准确的尺寸下载图片。输出图像应调整为正确的大小。我的代码:
<div>
<h3>Photo Taking Frame</h3>
<div id="frameholder">
<div id="resizable_frame">
<img src="./framee.png"/>
</div>
<div id="my_camera">
</div>
</div>
</div>
<div id="actions">
<h3>Action Buttons</h3>
<div>
<a href="javascript:void(take_snapshot())"><button>Take Snapshot</button></a>
</div>
</div>
<div id="output">
<div id="my_result"></div>
</div>
<script language="JavaScript">
// Adjust CSS according to this value #resizable_frame , #resizable_frame>img
var webcam_width = 480;
var webcam_height = 320;
var img_width = 126.72;
var img_height = 161.28;
var buffer = null;
Webcam.set({
// live preview size
width: webcam_width,
height: webcam_height,
// device capture size
dest_width: webcam_width,
dest_height: webcam_height,
image_format: 'png'
})
Webcam.attach( '#my_camera' );
function take_snapshot()
{
Webcam.snap( function(data_uri) {
let p = $( "#resizable_frame" ).first();
let position = p.position();
let resizable_frame_width = $('#resizable_frame').width();
let resizable_frame_height = $('#resizable_frame').height();
let img_data = crop (data_uri, position.left, position.top, resizable_frame_width, resizable_frame_height)
// console.log(img_data);
} );
// Webcam.freeze();
}
function crop (strDataURI, offsetX, offsetY, width, height)
{
buffer = document.createElement('canvas');
let b_ctx = buffer.getContext('2d');
let img = new Image();
let cropped = "";
// console.log(img)
img.onload = function() {
buffer.width = width;
buffer.height = height;
b_ctx.width = width;
b_ctx.height = height;
// draw the main canvas on our buffer one
b_ctx.drawImage(img, offsetX, offsetY, width, height , 0 , 0 , width , height);
}
img.src = strDataURI;
// document.getElementById('my_result').innerHTML = '<img src="'+strDataURI+'"/>';
setTimeout(function(){
let outImg = '<img id="outputImg" src="'+ buffer.toDataURL("image/png")+'"/>';
let dlBtn = "<a href='"+buffer.toDataURL("image/png")+ "' download>Download image</a>";
document.getElementById('my_result').innerHTML = outImg+'<br>'+dlBtn;
},1000)
}
function download_image(buffer){
dlimg = buffer.toDataURL("image/png");
var link = document.createElement('a');
link.download = "image.png";
link.href = dlimg.replace("image/png", "image/octet-stream");
link.click();
}
$('#resizable_frame').resizable({
aspectRatio: img_width / img_height,
maxHeight: webcam_height,
maxWidth: webcam_width,
minHeight: img_height,
minWidth: img_width
});
$( "#resizable_frame" ).draggable({
containment: "parent"
});
$('#resizable_frame').bind('resize', function(){
$('#resizable_frame>img').width($(this).width())
$('#resizable_frame>img').height($(this).height())
});
</script>