您好以下是我的代码。它只是一个html文件。我正试图用一个盒子裁剪图像。但是当我把它绘制到画布时,分辨率都会出错。请帮忙。
我需要剪切盒子所在的图像部分。
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style>
body,
html {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
#container {
width: 100%;
height: 100%;
position: fixed;
}
.cover-container {
display: table;
height: 315px;
margin: 5% auto 0;
width: 90%;
position: relative;
}
#camera {
height: 100%;
position: fixed;
width: 100%;
}
#camera2 {
height: 100%;
position: fixed;
width: 100%;
}
#cover {
display: block;
height: 315px;
left: 0;
/* position: absolute; */
top: 0;
width: 100%;
}
#capturebtn {
z-index: 9999;
width: 100%;
height: auto;
}
#capturebtn input {
width: 100px;
height: 50px;
margin: 0 auto;
right: 0;
bottom: 15px;
left: 0;
position: fixed;
}
@media(max-width:960px) and (min-width: 768px) {
#cover {
display: block;
height: 241px !important;
left: 0;
position: absolute;
top: 0;
width: 650px !important;
}
.cover-container {
display: table;
height: 241px;
margin: 5% auto 0;
width: 650px;
position: relative;
}
}
#capture {
left: -100px !important;
}
#reset {
left: 100px !important;
}
#crop {
left: 300px !important;
}
@media(max-width:767px) and (min-width: 360px) {
#cover {
display: block;
height: 185px !important;
left: 0;
position: absolute;
top: 0;
width: 500px !important;
}
.cover-container {
display: table;
height: 185px;
margin: 5% auto 0;
width: 500px;
position: relative;
}
}
</style>
<script>
var cropPicture = function () {
var cover = document.getElementById("cover");
var ctx = cover.getContext("2d");
var img = new Image();
img.onload = function () {
var position = $("#cover").offset();
//alert(JSON.stringify($("#cover").offset()));
//alert("cover width " + cover.width);
//alert("cover height" + cover.height);
//alert(position.left);
var coverLeft = position.left;
var coverTop = position.top;
var coverwidth = 851;
var coverheight = 315;
// var width = $('#cover').width();
// var parentWidth = $('#container').offsetParent().width();
// var percent = 100 * width / parentWidth;
//alert("percent " + percent);
alert("innerWidth " + window.innerWidth);
var destWidth = $('#cover').width();
var destHeight = $('#cover').height();
alert("destWidth " + destWidth);
ctx.drawImage(img, coverLeft, coverTop, coverwidth, coverheight, 0, 0, destWidth, destHeight);
//$("#source").css("display", "none");
}
img.src = document.getElementById("source").src;
}
</script>
<body>
<div id="container">
<div class="cover-container">
<canvas id="cover" height="315" width="851" style="border:1px solid #000"></canvas>
</div>
<img id="source" width="100%" height="100%" src="http://www.freedigitalphotos.net/images/img/homepage/87357.jpg">
</div>
<div id="capturebtn">
<input id="crop" type="button" value="Crop" onclick="cropPicture();" />
</div>
</body>
</html>