Skip to content

Instantly share code, notes, and snippets.

@agazso
Last active December 24, 2015 00:29
Show Gist options
  • Select an option

  • Save agazso/6717081 to your computer and use it in GitHub Desktop.

Select an option

Save agazso/6717081 to your computer and use it in GitHub Desktop.
Laserpointer with canvas
<html>
<head>
<script>
var canvas;
var points = [];
var timer;
var mousePos;
var prevPos;
function start() {
canvas = document.getElementById("canvas");
timer = setInterval(update, 20);
window.onmousemove = handleMouseMove;
mousePos = null;
prevPos = null;
}
function update() {
// samplePointer();
// redraw();
points.splice(0, 2);
redraw();
}
function samplePointer() {
if (mousePos === null) {
return;
}
console.log(prevPos, mousePos);
}
function redraw() {
if (canvas.getContext) {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');
drawCurve(ctx, points);
}
}
function handleMouseMove(event) {
event = event || window.event; // IE-ism
prevPos = mousePos;
mousePos = {
x: event.clientX,
y: event.clientY
};
if (prevPos != null && prevPos.x == mousePos.x && prevPos.y == mousePos.y) {
return;
}
points.push(mousePos.x);
points.push(mousePos.y);
if (points.length > 60) {
points.splice(0, 2);
}
redraw();
}
function drawCurve(ctx, pts) {
ctx.beginPath();
drawLines(ctx, pts);
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.lineWidth = 6;
ctx.stroke();
ctx.restore();
}
function drawLines(ctx, ppts) {
ctx.moveTo(ppts[0], ppts[1]);
for (var i = 0; i < ppts.length - 4; i += 2) {
var c = (ppts[i] + ppts[i+2]) / 2;
var d = (ppts[i+1] + ppts[i+3]) / 2;
ctx.quadraticCurveTo(ppts[i], ppts[i+1], c, d);
}
}
</script>
</head>
<body onload="start()" onresize="redraw()">
<canvas id="canvas"></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment