<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#nowpic{
}
.cutmark{
position: absolute;
border: 1px solid #fff;
}
#cutpic{
width: 250px;
height: 200px;
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="nowpic"></canvas>
<div class="cutmark" id="cutmark"></div>
<canvas id="cutpic"></canvas>
<script type="text/javascript">
var nowPic = document.getElementById("nowpic");
var cutMark = document.getElementById("cutmark");
var cutPic = document.getElementById("cutpic");
//设置原图宽高
nowPic.width = 500;
nowPic.height = 300;
cutImg(0,0,0,0);
var xStart = 0;
var yStart = 0;
var xEnd = 0;
var yEnd = 0;
nowPic.onmousedown = function(e) {
xStart = e.pageX;
yStart = e.pageY;
}
nowPic.onmouseup = function(e) {
xEnd = e.pageX;
yEnd = e.pageY;
cutImg(xStart,yStart,xEnd,yEnd);
}
/**
*
* @param xStart 起始点x
* @param yStart 起始点y
* @param xEnd 终点x
* @param yEnd 终点y
*/
function cutImg (xStart,yStart,xEnd,yEnd){
var dirtyWidth = xEnd - xStart;
var dirtyHeight = yEnd - yStart;
cutMark.style.width = dirtyWidth + 'px';
cutMark.style.height = dirtyHeight + 'px';
cutMark.style.left = xStart + "px";
cutMark.style.top = yStart + "px";
var nowText = nowPic.getContext("2d");//获取2d环境
var img1 = new Image();
// img1.crossOrigin="anonymous";
img1.src="img/1.jpg";
//为了实现图像的压缩和拉伸,创建一块新画布
var newCanvas = document.createElement("canvas");
var newText = newCanvas.getContext("2d");
img1.onload = function (){
nowText.drawImage(img1,0,0,nowPic.width,nowPic.height);//绘制图像
var imgData = nowText.getImageData(xStart,yStart,dirtyWidth,dirtyHeight);//获取截图画布像素数据
newCanvas.width = dirtyWidth;
newCanvas.height = dirtyHeight;
newText.putImageData(imgData,0,0,0,0,newCanvas.width,newCanvas.height);//将截取的图像放回画布上
var imgUrl = newCanvas.toDataURL("image/png");//将图片转为dataURL(base64)
var cutText = cutPic.getContext("2d");
var img2 = new Image();
img2.src = imgUrl;
img2.onload = function(){
cutText.drawImage(img2,0,0,cutPic.width,cutPic.height);//绘制图像
}
}
}
</script>
</body>
网友评论