Hey all,
Is there a better/faster way to track the mouse co-ords? Currently there is a noticeable delay when I move my mouse and the crosshair I’ve draw with canvas will follow it. I want the drawn cross always under the mouse, with no delay… Is it possible without changing my code to much?
Here is a minimal version of my script:
[CODE]var canvas,context,title,canvas;
var time = {
lastTick: 0
};
mouse = {
move: function(e) {
mouse.x = (e.clientX – canvas.offsetLeft)+window.scrollX;
mouse.y = (e.clientY – canvas.offsetTop)+window.scrollY;
},
down: function(e) {
if (mouse.active !== true) mouse.active = true;
mouse.button = e.button;
},
up: function(e) {
if (mouse.active !== false) mouse.active = false;
},
out: function(e) {
if (mouse.active !== false) mouse.active = false;
}
};
render = {
line: function(x,y,x2,y2) {
context.beginPath();
context.moveTo(x,y);
context.lineTo(x2,y2);
context.stroke();
context.closePath();
},
clear: function(x,y,h,w) {
context.clearRect(x,y,h,w);
}
};
function init() {
setSettings();
keepTime();
};
function setSettings() {
canvas = document.getElementById(“myCanvas”);
context = canvas.getContext(“2d”);
canvas.onmousemove = mouse.move;
canvas.onmousedown = mouse.down;
canvas.onmouseup = mouse.up;
canvas.onmouseout = mouse.out;
canvas.onclick = mouse.click;
canvas.ondblclick = mouse.dblclick;
document.title = “Canvas Webpage”;
canvas.w = canvas.clientWidth;
canvas.h = canvas.clientHeight;
time.lastTick = 0;
mouse.x = 0;
mouse.y = 0;
};
function keepTime() {
time.ticks = new Date().getMilliseconds();
time.delta = (time.ticks – time.lastTick);
//console.log(time.delta);
updatePage();
time.lastTick = time.ticks;
window.requestAnimationFrame(keepTime);
};
function updatePage() {
render.clear(0,0,canvas.w,canvas.h);
render.rect(0,0,canvas.w,canvas.h); //border
//crosshair
render.line(mouse.x-10,mouse.y,mouse.x-5,mouse.y);
render.line(mouse.x+5,mouse.y,mouse.x+10,mouse.y);
render.line(mouse.x,mouse.y-10,mouse.x,mouse.y-5);
render.line(mouse.x,mouse.y+5,mouse.x,mouse.y+10);
};
if needed:
[code=html]<!DOCTYPE html>
<html>
<head>
<title>?no javascript?</title>
<script src=”test.js”></script>
<style>
* {
margin: 0;
padding: 0;
border: 0;
}
#wrapper {
width: 1000px;
height: 800px;
margin: 10px auto 10px auto;
}
#myCanvas:hover {
cursor: crosshair;
}
</style>
</head>
<body onload=”init()”>
<div id=”wrapper”>
<canvas id=”myCanvas” width=”1000″ height=”800″>no canvas</canvas>
</div>
</body>
</html>
Any help/advice will be appreciated.