JavaScript+HTML5 canvas实现放大镜效果完整示例
程序员文章站
2022-10-13 21:30:48
本文实例讲述了javascript+html5 canvas实现放大镜效果。分享给大家供大家参考,具体如下:
效果:
本文实例讲述了javascript+html5 canvas实现放大镜效果。分享给大家供大家参考,具体如下:
效果:
<!doctype html> <html> <head lang="en"> <meta charset="utf-8"> <title>www.jb51.net canvas放大镜</title> <style> #copycanvas { border: 1px solid #000; display: none; } #square { width: 90px; height: 90px; background-color: #cc3; border: 1px solid #f00; opacity: 0.5; position: absolute; z-index: 999; display: none; cursor: crosshair; } </style> </head> <body> <canvas id="canvas" width="450" height="676"></canvas> <canvas id="copycanvas" width="300" height="300"></canvas> <div id="square"></div> <script> var canvas = document.getelementbyid('canvas'), //获取canvas对象 context = canvas.getcontext('2d'), //获取上下文 copycanvas = document.getelementbyid('copycanvas'), //获取copycanvas copycontext = copycanvas.getcontext('2d'), square = document.getelementbyid('square'), //获取透明框 squaredata = {}, //用来保存选择框数据 box = canvas.getboundingclientrect(); //getboundingclientrect方法可以获取元素上、下、左、右分别相对浏览器的坐标位置 //创建图像对象,并加载 image = new image(); image.src = "3.jpg"; image.onload = function(){ context.drawimage(image,0,0,canvas.width,canvas.height); }; canvas.onmouseover = function(e){ var x = e.clientx, //获取鼠标实时坐标 y = e.clienty; createsquare(x,y); //保存透明选择框属性 }; window.onmousemove = function(e){ var x = e.clientx, y = e.clienty; //判断鼠标是否移出canvas if(x >= canvas.offsetleft && x <= canvas.offsetleft + canvas.width && y >= canvas.offsettop && y <= canvas.offsettop + canvas.height){ createsquare(x,y); }else{ hidesquare(); hidecanvas(); } } function showsquare(){ square.style.display = 'block'; } function hidesquare(){ square.style.display = 'none'; } function showcanvas(){ copycanvas.style.display = "inline"; } function hidecanvas(){ copycanvas.style.display = "none"; } function createsquare(x,y){ //控制选择框不移动出canvas x = x - 45 < canvas.offsetleft ? canvas.offsetleft:x - 45; y = y - 45 < canvas.offsettop ? canvas.offsettop:y - 45; x = x + 90 < box.right ? x:box.right - 90; y = y + 90 < box.bottom ? y:box.bottom - 90; squaredata.left = x; squaredata.top = y; movesquare(x,y); } function movesquare(x,y){ square.style.left = x + "px"; square.style.top = y + "px"; showcanvas(); showsquare(); copy(); } function copy(){ copycontext.drawimage( canvas, squaredata.left - box.left, squaredata.top - box.top, 90, 90, 0, 0, copycanvas.width, copycanvas.height ); } </script> </body> </html>
感兴趣的朋友可使用在线html/css/javascript代码运行工具:http://tools.jb51.net/code/htmljsrun测试一下运行效果。
更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript图片操作技巧大全》、《javascript运动效果与技巧汇总》、《javascript+html5特效与技巧汇总》、《javascript图形绘制技巧总结》、《javascript数据结构与算法技巧总结》及《javascript数学运算用法总结》
希望本文所述对大家javascript程序设计有所帮助。