採用canvas實現放大鏡功能,只需要使用一個方法。。。
這個方法有三種使用情況:
1、drawImage(img,x,y)
三個參數,第一個參數當然是img元素了,也可以是video元素或者Image對象,x 、y 爲圖片繪製時在畫布中的起始座標,圖像大小與原圖相同。
2、drawImage(img , x , y , w , h)
與第一中情況相比,多了兩個參數,分別代表所繪圖像的寬度和高度。
3、drawImage(img , sx , sy , sw , sh , dx , dy , dw , dh);
9個參數,分別是:圖像元素,被複制區域在原畫布中的起始橫座標、被複制區域在原畫布中的起始縱座標、被複制區域的寬度、被複制區域的高度、複製後目標圖像在畫布中的起始橫座標、複製後目標圖像在畫布中的起始縱座標、複製後目標圖像的寬度、複製後目標圖像的高度。
因此這種情況下可以將某幅圖像的局部區域複製到另一個畫布中的某個位置。
效果圖:
代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>cavas放大鏡</title>
<style type="text/css">
.wrap {width: 1000px; height: 650px; border: 1px solid black; margin: auto; position: relative; overflow: hidden;}
#canvas {border: 1px solid black; border-radius: 50%; position: absolute; display: none;}
#myCanvascanvas {border: 1px solid black;}
</style>
</head>
<body>
<div class="wrap">
<canvas id="myCanvas" width="" height=""></canvas>
<canvas id="canvas" width="150" height="150"></canvas>
</div>
</body>
<script type="text/javascript">
var wrap = document.querySelector('.wrap');
var imgCanvas = document.querySelector('#myCanvas');
var canvas = document.querySelector('#canvas');
var context = imgCanvas.getContext('2d');
var con = canvas.getContext('2d');//設置繪製環境
imgCanvas.width = wrap.offsetWidth; //畫布寬度
imgCanvas.height = wrap.offsetHeight;//畫布高度
var img = new Image();//定義一個img對象
img.src = 'img/7a79e1edab64034f924b368eafc379310b551d32.jpg';
//圖片加載事件
img.onload = function(){
img.width= imgCanvas.width;
img.height= imgCanvas.height;
context.drawImage(img,0,0);
con.drawImage(img,0,0);
}
//鼠標移入事件
wrap.addEventListener('mouseover',down,false);
//鼠標移除出事件
wrap.addEventListener('mouseout',up,false);
function down(){
canvas.style.display = 'block';
//鼠標移動事件
wrap.addEventListener('mousemove',move,false);
}
function move(){
var ev = window.event || event;
//使鼠標顯示在畫布的中間
var newX = ev.clientX - canvas.width/2 - wrap.offsetLeft;
var newY = ev.clientY - canvas.height/2 - wrap.offsetTop;
canvas.style.top = newY + 'px';
canvas.style.left = newX + 'px';
con.drawImage(img,newX + 40, newY + 40, 150,150,0,0,300,300);
}
function up(){
canvas.style.display = 'none';
//移除鼠標移動事件
imgCanvas.removeEventListener('mousemove',move,false);
}
</script>
</html>