HTML5 Canvas Control - Record / Replay Mouse Motion
Fiddle exploring how to use a canvas control to -- (1) plot the positon of the cursor by drawing rectangles on the canvas as the mouse is moved over it;
(2) after clearing the canvas, create replay effect by redrawing the same set rectangles in time delayed sequence
HTML
<div class="page-header">
<h3> Canvas Mouse Record and Restore</h3>
</div>
<div class="container enter-stage-south">
<div class="row">
<canvas id="fiddleHook" width="300" height="300" style="background-color:#ffffff; cursor: default; width:300px;height:300px;border:1px solid black;"></canvas>
</div>
<div class="row">
<div class="navbar">
<input type="button" value="clear" id="btnClear">
<input type="button" value="replay" id="btnRestore">
</div>
<p>
<ul>
<li>"Click and Drag" the mouse to create a drawing</li>
</ul>
</p>
</div>
</div>
CSS
.enter-stage-south {
-moz-animation-duration: 3s;
-webkit-animation-duration: 3s;
-moz-animation-name: slide-up;
-webkit-animation-name: slide-up;
}
@-moz-keyframes slide-up {
from {
margin-top: 100%;
}
to {
margin-top: 0%;
}
}
@-webkit-keyframes slide-up {
from {
margin-top: 100%;
}
to {
margin-top: 0%;
}
}
JavaScript
(function (app, $, undefined) {
$(document).ready(function () {
console.log('document ready');
$("#fiddleHook").on("mousemove", app.onCanvasMouseMove);
$("#btnClear").on("click", app.onButtonClearClick);
$("#btnRestore").on("click", app.onButtonRestoreClick);
app.canvas = document.getElementById("fiddleHook");
});
app.model = {
point: {
x: 0,
y: 0
}
};
app.buffer = [];
app.onCanvasMouseMove = function (e) {
if (e.which === 1) {
var rect = app.canvas.getBoundingClientRect(),
pt = Object.create(app.model.point);
pt.x = e.clientX - rect.left;
pt.y = e.clientY - rect.top;
app.buffer.push(pt);
app.drawRect(pt);
}
};
app.onButtonClearClick = function (ctrl) {
app.clearCanvas();
app.buffer = [];
};
app.onButtonRestoreClick = function (ctrl) {
var i = 0,
pt = null,
delay = 100;
app.clearCanvas();
if (app.buffer.length > 0) {
for (i; i < app.buffer.length; i++) {
pt = app.buffer[i];
app.drawRect(pt, delay);
delay = delay + 50;
}
}
};
app.drawRect = function (pt, delay) {
var ctx = app.canvas.getContext("2d");
if (delay) {
setTimeout('app.canvas.getContext("2d").fillRect(' + pt.x + ',' + pt.y + ', 8, 6);', delay);
} else {
ctx.fillRect(pt.x, pt.y, 8, 6);
}
};
app.clearCanvas = function () {
var c = app.canvas,
ctx = c.getContext('2d');
ctx.clearRect(0, 0, c.width, c.height);
};
})(window.app = window.app || {}, jQuery)