<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>放大镜canvas版</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#canvas{
display: block;
margin: 0 auto;
box-shadow: 2px 3px 10px 5px gray;
}
</style>
</head>
<body>
<canvas id="canvas" width="477" height="476"></canvas>
</body>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// 创建图片
var img = new Image();
img.src = 'img/4.jpg';
img.onload = function(){
context.drawImage(img,0,0);
}
// 添加鼠标事件
canvas.onmousedown = function(){
canvas.onmousemove = function(e){
// 清除画布
context.clearRect(0,0,canvas.width,canvas.height);
// 再次绘制图片到画布上
context.drawImage(img,0,0);
var event = window.event e;
var x = event.clientX - canvas.offsetLeft;
var y = event.clientY - canvas.offsetTop;
// 开始绘制放大区域
context.drawImage(img,x-50,y-50,100,100,x-70,y-70,140,140);
}
}
// 鼠标移出事件
canvas.onmouseleave = function(){
// 清除鼠标移动事件
canvas.onmousemove = null;
// 清除画布
context.clearRect(0,0,canvas.width,canvas.height);
// 再次绘制图片到画布上
context.drawImage(img,0,0);
}
</script>
</html>
打开App,阅读手记