arrowcounter/score/static/js/score.js
Claudio Maggioni (maggicl) 139225a1f6 Added drag support on scores
2019-08-16 14:59:56 +02:00

76 lines
2 KiB
JavaScript

// vim: set ts=2 sw=2 et tw=80:
$(document).ready(() => {
const TARGET_EVENTS = $('.target-events');
const SCORES = [
{ name: 'X', maxRadius: 0.025 },
{ name: '10', maxRadius: 0.05 },
{ name: '9', maxRadius: 0.1 },
{ name: '8', maxRadius: 0.15 },
{ name: '7', maxRadius: 0.2 },
{ name: '6', maxRadius: 0.25 },
{ name: '5', maxRadius: 0.3 },
{ name: '4', maxRadius: 0.35 },
{ name: '3', maxRadius: 0.4 },
{ name: '2', maxRadius: 0.45 },
{ name: '1', maxRadius: 0.5 }
];
function score(radius) {
for (let score of SCORES) {
if (radius <= score.maxRadius) {
return score.name;
}
}
return 'M';
};
TARGET_EVENTS.on('mousemove', e => {
if (TARGET_EVENTS.data('dragging')) {
const left = e.originalEvent.pageX - TARGET_EVENTS.offset().left;
const top = e.originalEvent.pageY - TARGET_EVENTS.offset().top;
markScore(left, top, TARGET_EVENTS.data('dragging')[0]);
}
});
TARGET_EVENTS.on('mouseup', e => {
let $marker = TARGET_EVENTS.data('dragging');
if ($marker) {
$marker.removeClass('orange');
$marker.addClass('teal');
TARGET_EVENTS.data('dragging', null);
} else {
markScore(e.originalEvent.offsetX, e.originalEvent.offsetY, false);
}
});
function markScore(left, top, marker) {
const targetRadius = TARGET_EVENTS.width();
const x = -0.5 + left / targetRadius;
const y = -0.5 + top / targetRadius;
const radius = Math.sqrt(x * x + y * y);
if (!marker) {
marker = document.createElement("div");
const $marker = $(marker);
$marker.on('mousedown', e => {
TARGET_EVENTS.data('dragging', $marker);
$marker.removeClass('teal');
$marker.addClass('orange');
e.preventDefault();
});
marker.className = "score-marker teal";
TARGET_EVENTS.append(marker);
}
marker.style.left = (x + 0.5) * 100 + "%";
marker.style.top = (y + 0.5) * 100 + "%";
console.log(x, y, score(radius));
};
});