<!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>
Canvas实现图片裁剪
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...