canvas实现图像截取功能
本文实例为大家分享了canvas图像截取的具体代码,供大家参考,具体内容如下
<!DOCTYPEhtml>
<html>
<headlang="en">
<metacharset="UTF-8">
<title>canvas-图像截取</title>
<style>
canvas{
border:1pxdashedred;
float:left;
position:relative;
}
</style>
</head>
<body>
<divid="cantox"style="position:relative">
<canvasid="oldcanvas"width="500px"height="300px">
</canvas>
<divid="cliptox"style="position:absolute;display:none"></div>
</div>
<buttonid="btnclip"style="float:left">截取该区域</button>
<canvasid="nowcanvas"width="500px"height="300px">
</canvas>
<script>
//获取div元素
varcantox=document.getElementById("cantox");
varcliptox=document.getElementById("cliptox");
varbtnclip=document.getElementById("btnclip");
//获取到canvas元素
varoldcanvas=document.getElementById("oldcanvas");
varnowcanvas=document.getElementById("nowcanvas");
//获取canvas中的画图环境
varoldcontext=oldcanvas.getContext('2d');
varnowcontext=nowcanvas.getContext('2d');
varimg=newImage();
img.src="./image/liuyifei.jpg";
//加载图像到canvas画布中
window.onload=function(){
oldcontext.drawImage(img,0,0,oldcanvas.width,oldcanvas.height);
}
varstartPoint;//截取图像开始坐标
varendPoint;//截图图像的结束坐标
varw;//截取图像的宽度
varh;//截取图像的高度
varflag=false;//用于判断移动事件事物控制
//鼠标按下事件
cantox.onmousedown=function(e){
flag=true;
cliptox.style.display='block';
startPoint=windowToCanvas(oldcanvas,e.clientX,e.clientY);
cliptox.style.left=startPoint.x+'px';
cliptox.style.top=startPoint.y+'px';
}
//鼠标移动事件
cantox.onmousemove=function(e){
if(flag){
cliptox.style.background='rgba(0,0,0,0.5)';
endPoint=windowToCanvas(oldcanvas,e.clientX,e.clientY);
w=endPoint.x-startPoint.x;
h=endPoint.y-startPoint.y;
cliptox.style.width=w+'px';
cliptox.style.height=h+'px';
}
}
//鼠标释放事件
cantox.onmouseup=function(e){
flag=false;
}
//按钮截取事件
btnclip.onclick=function(){
imgCut(nowcontext,img,oldcanvas.width,oldcanvas.height,startPoint.x,startPoint.y,w,h);
}
/*
*图像截取函数
*context:绘制环境对象
*image:图像对象
*imgElementW:图像显示的宽度
*imgElementH:图像显示的高度
*sx:截取图像的开始X坐标
*sy:截取图像的开始Y坐标
*w:截取图像的宽度
*h:截取图像的高度
**/
functionimgCut(context,image,imgElementW,imgElementH,sx,sy,w,h){
//清理画布,便于重新绘制
context.clearRect(0,0,imgElementW,imgElementH);
//计算:比例=原图像/显示图像
varratioW=image.width/imgElementW;
varratioH=image.height/imgElementH;
//根据截取图像的所占位置及大小计算出在原图所占的位置及大小
//.drawImage(图像对象,原图像截取的起始X坐标,原图像截取的起始Y坐标,原图像截取的宽度,原图像截取的高度,
//绘制图像的起始X坐标,绘制图像的起始Y坐标,绘制图像所需要的宽度,绘制图像所需要的高度);
context.drawImage(image,ratioW*sx,ratioH*sy,ratioW*w,ratioH*h,0,0,w,h);
}
/*
*坐标转换:将window中的坐标转换到元素盒子中的坐标,并返回(x,y)坐标
*element:canvas元素对象
*x:鼠标在当前窗口X坐标值
*y:鼠标在当前窗口Y坐标值
**/
functionwindowToCanvas(element,x,y){
//获取当前鼠标在window中的坐标值
//alert(event.clientX+"-------"+event.clientY);
//获取元素的坐标属性
varbox=element.getBoundingClientRect();
varbx=x-box.left;
varby=y-box.top;
return{x:bx,y:by};
}
</script>
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。