Skip to content

Instantly share code, notes, and snippets.

@Slowhand0309
Last active August 31, 2018 14:46
Show Gist options
  • Save Slowhand0309/ba21b6cdad5fb4362284676f58217f39 to your computer and use it in GitHub Desktop.
Save Slowhand0309/ba21b6cdad5fb4362284676f58217f39 to your computer and use it in GitHub Desktop.
Loupe on html5 canvas.
/**
* canvas_loupe.js
*/
var loupe = {
x: 0, // Current x.
y: 0, // Current y.
w: 0, // Image width.
h: 0, // Image height.
loupe_x: 50, // loupe x coordinate.
loupe_y: 50, // loupe y coordinate.
size: 50, // Crop size.
zoom: 2, // Zoom rate.
wide_size: 0, // Crop size * Zoom rate.
image: null, // Image object.
/**
* Initialize.
*
* @param w Image width
* @param h Image height
* @param src Image src
*/
initialize: function(w, h, src) {
this.w = w;
this.h = h;
this.wide_size = this.size * this.zoom;
this.image = new Image();
this.image.src = src;
},
/**
* Update coordinate.
*
* @param x
* @param y
*/
update: function(x, y) {
this.x = x;
this.y = y;
},
/**
* Draw loupe.
*
* @param ctx context
*/
draw: function(ctx) {
var nx = (this.x * this.image.naturalWidth / this.w) - (this.size / 2);
var ny = (this.y * this.image.naturalHeight / this.h) - (this.size / 2);
ctx.save();
ctx.beginPath();
ctx.arc(this.loupe_x + this.wide_size / 2,
this.loupe_y + this.wide_size / 2, this.wide_size / 2, 0, Math.PI * 2, false);
ctx.clip();
ctx.drawImage(this.image, nx, ny, this.size, this.size,
this.loupe_x, this.loupe_y, this.wide_size, this.wide_size);
ctx.restore();
}
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>loupe</title>
<script type="text/javascript" src="canvas_loupe.js"></script>
<script type="text/javascript" src="index.js"></script>
<style>
#container {
position: relative;
}
#main_img {
width: 640px;
height: 480px;
position: absolute;
z-index: 1;
}
#loupe_canvas {
position: absolute;
z-index: 2;
}
</style>
</head>
<body>
<div id="container">
<img id="main_img" src="sample.jpg"></img>
<canvas id="loupe_canvas" width="640" height="480"></canvas>
</div>
</body>
</html>
var ctx = null;
window.onload = function() {
var canvas = document.getElementById('loupe_canvas');
ctx = canvas.getContext('2d');
canvas.addEventListener('mousemove', onMouseMove);
loupe.initialize(640, 480, 'sample.jpg');
};
function onMouseMove(e) {
loupe.update(e.clientX, e.clientY);
loupe.draw(ctx);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment