js canvas实现放大镜查看图片功能
程序员文章站
2022-04-10 10:13:56
本文实例为大家分享了canvas实现放大镜查看图片功能的具体代码,供大家参考,具体内容如下
本文实例为大家分享了canvas实现放大镜查看图片功能的具体代码,供大家参考,具体内容如下
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>title</title> </head> <body style="background: black;"> <canvas id="mycanvas" style="display: block;margin: 0px auto;border: 10px solid #aaa "> 你的浏览器不支持canvas </canvas> <canvas id="offcanvas" style="display: none"></canvas> <script> var mycanvas = document.getelementbyid("mycanvas"); var context = mycanvas.getcontext("2d"); var offcanvas = document.getelementbyid("offcanvas"); var offcontext = offcanvas.getcontext("2d"); var ismousedown = false; var scale; var image = new image(); window.onload = function () { mycanvas.width = 300; mycanvas.height = 200; image.src = "1.jpg"; image.onload = function () { offcanvas.width = image.width; offcanvas.height = image.height; scale = offcanvas.width / mycanvas.width ; context.drawimage(image,0,0,mycanvas.width,mycanvas.height); offcontext.drawimage(image,0,0); } }; function windowtocanvas(x,y) { var bbox = mycanvas.getboundingclientrect(); return { x : x - bbox.left , y : y - bbox.top}; } mycanvas.onmousedown = function (e) { e.preventdefault(); var point = windowtocanvas(e.clientx , e.clienty); console.log(point); ismousedown = true; drawcanvaswithmagnifier( true , point ); }; mycanvas.onmousemove = function (e) { e.preventdefault(); if (ismousedown ){ var point = windowtocanvas(e.clientx , e.clienty); drawcanvaswithmagnifier( true , point ); } }; mycanvas.onmouseup = function (e) { e.preventdefault(); ismousedown = false; drawcanvaswithmagnifier( false ); }; mycanvas.onmouseout = function (e) { e.preventdefault(); ismousedown = false; drawcanvaswithmagnifier( false ); }; function drawcanvaswithmagnifier( isshowmagnifier , point) { context.clearrect(0,0,mycanvas.width,mycanvas.height); context.drawimage(image,0,0,mycanvas.width,mycanvas.height); if(isshowmagnifier == true ){ drawmagnifier( point ); } } function drawmagnifier( point ) { var imagelg_cx = point.x * scale ; var imagelg_cy = point.y * scale ; var mr = 20 ; var sx = imagelg_cx - mr ; var sy = imagelg_cy - mr ; var dx = point.x - mr ; var dy = point.y - mr ; context.save(); context.linewidth = 5.0; context.strokestyle = "#069"; context.beginpath(); context.arc(point.x,point.y,mr,0,math.pi*2); context.stroke(); context.clip(); context.drawimage(offcanvas,sx,sy,2*mr,2*mr,dx,dy,2*mr,2*mr); context.restore(); } </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。