univ.phundrak.fr/js/canvas.js

59 lines
1.9 KiB
JavaScript

var canvas;
var loupe;
var img;
var ratio;
var topmargin;
window.onload = function() {
canvas = document.getElementById("canvastp1");
var context = canvas.getContext("2d");
img = document.getElementById("ardeche");
var hRatio = canvas.width / img.width;
var vRatio = canvas.height / img.height;
ratio = Math.min(hRatio, vRatio);
topmargin = (canvas.height - img.height * ratio) / 2;
context.drawImage(img, 0, 0, img.width, img.height,
0, topmargin, img.width * ratio, img.height * ratio);
canvas.addEventListener('mousemove', zoom, false);
canvas.addEventListener('mouseout', hide, false);
loupe = document.getElementById("loupe");
context = loupe.getContext("2d");
context.drawImage(img, 0, 0);
};
function zoom(evt) {
var mousePos = getMousePos(canvas, evt); /* get mouse position */
loupe.style.display = "inline"; /* make glass visible */
/* process x axis */
var canvasXMargin = window.getComputedStyle(canvas).getPropertyValue('margin-left');
canvasXMargin = canvasXMargin.substr(0, canvasXMargin.length - 2);
var marginLeft = Number(canvasXMargin) + mousePos.x + 15;
loupe.style.marginLeft = marginLeft + "px";
/* process y axis */
var marginTop = mousePos.y + 15;
loupe.style.marginTop = marginTop + "px";
var actualPos = mousePos.y - topmargin;
/* clear and redraw glass */
var context = loupe.getContext("2d");
context.clearRect(0, 0, loupe.width, loupe.height);
context.drawImage(img,
(mousePos.x - loupe.width / 8) / ratio, (actualPos - loupe.height / 8) / ratio,
loupe.width, loupe.height, 0, 0, loupe.width, loupe.height);
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function hide() {
loupe.style.display = "none";
}