1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> <style> canvas { display: block; margin: 0 auto; border: 1px solid #222; } </style> </head> <body> <canvas id="my-canvas"></canvas> <canvas id="off-canvas" style="display: none;"></canvas> <script> var isMouseDown = false, scale = 1.0; var canvas = document.querySelector("#my-canvas"); var offCanvas = document.querySelector("#off-canvas"); var ctx = canvas.getContext("2d"); var offCtx = offCanvas.getContext("2d"); var img = new Image(); window.onload = function() { img.src = "./img/photo.jpg"; img.onload = function() { canvas.width = img.width; canvas.height = img.height; offCanvas.width = img.width; offCanvas.height = img.height; scale = offCanvas.width / canvas.width; ctx.drawImage(img, 0, 0, canvas.width, canvas.height); offCtx.drawImage(img, 0, 0, canvas.width, canvas.height); }; canvas.onmousedown = function(event) { event.preventDefault(); var point = windowToCanvas(event.clientX, event.clientY); isMouseDown = true; drawCanvasWithMagnifier(true, point); }; canvas.onmousemove = function(event) { event.preventDefault(); if (isMouseDown === true) { var point = windowToCanvas( event.clientX, event.clientY ); drawCanvasWithMagnifier(true, point); } }; canvas.onmouseup = function(event) { event.preventDefault(); isMouseDown = false; drawCanvasWithMagnifier(false); }; canvas.onmouseout = function(event) { event.preventDefault(); isMouseDown = false; drawCanvasWithMagnifier(false); }; };
function windowToCanvas(x, y) { var bbox = canvas.getBoundingClientRect(); return { x: x - bbox.x, y: y - bbox.y }; } function drawCanvasWithMagnifier(isShow, point) { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); if (isShow) { var { x, y } = point; var mr = 50; var sx = x - mr / 2, sy = y - mr / 2; var dx = x - mr, dy = y - mr; ctx.drawImage( offCanvas, sx, sy, mr, mr, dx, dy, 2 * mr, 2 * mr ); } } </script> </body> </html>
|