Skip to content

Instantly share code, notes, and snippets.

@joshvermaire
Created March 16, 2012 05:28
Show Gist options
  • Save joshvermaire/2048650 to your computer and use it in GitHub Desktop.
Save joshvermaire/2048650 to your computer and use it in GitHub Desktop.
Canvas
canvas {
position: absolute;
left: 0;
top: 0;
}​
<img src="http://placekitten.com/400/600" width="400" height="600"/>
<canvas id="canvas" width="400" height="600"></canvas>​
var x, y, startx, starty;
var canvasWidth = 400;
var canvasHeight = 600;
var canvas = document.getElementById('canvas');
var $canvas = $(canvas);
var ctx = canvas.getContext('2d');
ctx.strokeStyle = "rgb(255,255,255)";
ctx.lineWidth = 4;
var draw = function(e) {
var trueWidth = x-startx;
var trueHeight = y-starty;
var absH = Math.abs(trueHeight);
var absW = Math.abs(trueWidth);
var negH = (trueHeight < 0) ? -1 : 1;
var negW = (trueWidth < 0) ? -1 : 1;
var height = (absW > absH) ? absW * negH : absH * negH;
var width = (absW > absH) ? absW * negW : absH * negW;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.strokeRect(startx, starty, width, height);
}
var requestAnimFrame;
requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
return window.setTimeout(callback, 1000 / 60);
};
})();
var mousemove = function(e) {
getCoords(e);
requestAnimFrame(draw);
}
var getCoords = function(e) {
x = e.pageX;
y = e.pageY;
}
$canvas.on('mousedown', function(e) {
startx = x = e.pageX;
starty = y = e.pageY;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
canvas.addEventListener('mousemove', mousemove, false);
});
$canvas.on('mouseup', function() {
canvas.removeEventListener('mousemove', mousemove, false);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment