效果截图:
JS代码:
<script> // 初始化canvas01和上下文环境 var cav01 = document.getElementById('cav01'); var cxt01 = cav01.getContext('2d'); // 初始化canvas02和上下文环境 var cav02 = document.getElementById('cav02'); var cxt02 = cav02.getContext('2d'); //初始化image对象和缩放比例 var oImg = new Image(); var scale; window.onload = function(){ //设置图片路径 oImg.src = 'images/02.jpg'; //设置主canvas的宽高 cav01.width = 800; cav01.height = 500; oImg.onload = function(){ //设置离屏canvas的宽高,与原始图片的宽高一致 cav02.width = oImg.width; cav02.height = oImg.height; //初始化鼠标按下状态和设置缩放比例 var isMouseDown = false; scale = cav02.width/cav01.width; //绘制图像到canvas,第二个canvas初始时是隐藏的 cxt01.drawImage( oImg, 0, 0, cav01.width, cav01.height); cxt02.drawImage( oImg, 0, 0, cav02.width, cav02.height); //鼠标按下状态 cav01.onmousedown = function(e){ //获取鼠标相对于canvas的坐标 var pos = getMousePos(e.clientX,e.clientY); //阻止鼠标默认事件 e.preventDefault(); //调用绘制放大镜方法 drawFilterImg(true,pos); //把isMouseDown标记设置为true; isMouseDown = true; } //鼠标移动状态 cav01.onmousemove = function(e){
//获取鼠标相对于canvas的坐标 var pos = getMousePos(e.clientX,e.clientY); e.preventDefault(); //根据isMouseDown状态,调用绘制放大镜方法 if(isMouseDown == true ){ drawFilterImg(true,pos); } } // 鼠标抬起状态 cav01.onmouseup = function(e){ //获取鼠标相对于canvas的坐标 var pos = getMousePos(e.clientX,e.clientY); e.preventDefault(); //调用绘制放大镜方法 drawFilterImg(false); //把isMouseDown状态设置为false isMouseDown = false; } } // 绘制放大镜方法 flag:用于判断是否开始绘制,pos:鼠标相对于canvas画布的坐标 function drawFilterImg(flag,pos){ //每次调用先清空canvas画布,避免出现重复图像 cxt01.clearRect( 0, 0, cav01.width, cav01.height); cxt01.drawImage( oImg, 0, 0, cav01.width, cav01.height); //定义放大镜半径 var r = 100; if(flag == true){ //调用绘制放大区域方法 drawFilterImgCon(pos,r); } } //绘制放大区域方法 function drawFilterImgCon(pos,r){ //大图图像上开始剪切的坐标 var sx = pos.x*scale - r; var sy = pos.y*scale - r; //画在canvas上的坐标 var dx = pos.x - r; var dy = pos.y - r; cxt01.save(); cxt01.strokeStyle = 'rgba(0,0,0,0.3)'; cxt01.lineWidth = 2; cxt01.beginPath(); cxt01.arc( pos.x, pos.y, r, 0 , Math.PI*2); cxt01.stroke(); cxt01.clip(); cxt01.drawImage( cav02, sx, sy, r*2, r*2, dx, dy, r*2, r*2); cxt01.restore(); } //定义获取鼠标在canvas上位置的方法 //x:鼠标距离窗口的x坐标,y:鼠标距离窗口的y坐标 function getMousePos(x,y){ var oCanPos = cav01.getBoundingClientRect(); return { x: x-oCanPos.left, y: y-oCanPos.top } } } </script>
HTML代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>canvas图片放大镜</title> <style> body{ background-color: #333; padding-top: 60px; } #cav01{ display: block; margin: 0 auto; } #cav02{ display: none;} </style> </head> <body> <!-- 主canvas --> <canvas id="cav01" style="border:1px solid #666;"></canvas> <!-- 离屏canvas,用于放置放大的图片,默认状态为隐藏 --> <canvas id="cav02"></canvas> </body> </html>