var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 512;
canvas.height = 512;
canvas.style.border = "1px solid black";
document.body.appendChild(canvas);
var renderSaveCount = 0;
var arrow = {
x : 256,
y : 156,
image : new Image()
};
var mouse = {
x : null,
y : null,
changed : false,
changeCount : 0,
}
arrow.image.src = 'https://d30y9cdsu7xlg0.cloudfront.net/png/35-200.png';
function drawImageLookat(img, x, y, lookx, looky){
ctx.setTransform(1, 0, 0, 1, x, y);
ctx.rotate(Math.atan2(looky - y, lookx - x) - Math.PI / 2);
ctx.drawImage(img, -img.width / 2, -img.height / 2);
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
function drawCrossHair(x,y,color){
ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(x - 10, y);
ctx.lineTo(x + 10, y);
ctx.moveTo(x, y - 10);
ctx.lineTo(x, y + 10);
ctx.stroke();
}
function mouseEvent(e) {
var bounds = canvas.getBoundingClientRect();
mouse.x = e.pageX - bounds.left;
mouse.y = e.pageY - bounds.top;
mouse.cx = e.clientX - bounds.left;
mouse.cy = e.clienY - bounds.top;
mouse.changed = true;
mouse.changeCount += 1;
}
document.addEventListener("mousemove",mouseEvent);
var renderTimeTotal = 0;
var renderCount = 0;
ctx.font = "18px arial";
ctx.lineWidth = 1;
function update(){
if(arrow.image.complete && mouse.changed){
var now = performance.now();
mouse.changed = false;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var x = mouse.x - scrollX;
var y = mouse.y - scrollY;
drawImageLookat(arrow.image, arrow.x, arrow.y, x ,y);
drawCrossHair(x,y,"black");
drawCrossHair(mouse.cx,mouse.cy,"rgba(255,100,100,0.2)");
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.globalAlpha = 0.2;
ctx.moveTo(arrow.x, arrow.y);
ctx.lineTo(x, y);
ctx.stroke();
ctx.globalAlpha = 1;
renderSaveCount += mouse.changeCount -1;
mouse.changeCount = 0;
var timeSaved = ((renderTimeTotal / renderCount) * renderSaveCount);
var timeRatio = ((timeSaved / renderTimeTotal) * 100).toFixed(0);
ctx.fillText("Avoided "+ renderSaveCount + " needless renders. Saving ~" + timeSaved.toFixed(0) +"ms " + timeRatio + "% .",10,20);
renderTimeTotal += performance.now()-now;
renderCount += 1;
}
requestAnimationFrame(update);
}
requestAnimationFrame(update);