function log() {
console.log.apply(console, arguments);
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
function reOffset() {
var BB = canvas.getBoundingClientRect();
offsetX = BB.left;
offsetY = BB.top;
}
var offsetX, offsetY;
reOffset();
window.onscroll = function(e) {
reOffset();
}
window.onresize = function(e) {
reOffset();
}
var isDown = false;
var startX, startY;
var cx = cw / 2;
var cy = ch / 2;
var radius = 100;
var startAngle = Math.PI/6;
var enemyRadius = 15;
var shieldStrokeWidth = 8;
var endRadians = enemyRadius / (2 * Math.PI * radius) * (Math.PI * 2);
defineShieldHitPath(cx, cy, radius, enemyRadius, startAngle);
drawShield(cx, cy, radius, startAngle, shieldStrokeWidth);
$("#canvas").mousemove(function(e) {
handleMouseMove(e);
});
function defineShieldHitPath(cx, cy, r, enemyRadius, startAngle) {
ctx.beginPath();
ctx.arc(cx, cy, r - enemyRadius - shieldStrokeWidth / 2, startAngle - endRadians, startAngle + Math.PI + endRadians);
ctx.arc(cx, cy, r + enemyRadius + shieldStrokeWidth / 2, startAngle + Math.PI + endRadians, startAngle - endRadians, true);
ctx.closePath();
ctx.lineWidth = 1;
ctx.strokeStyle = 'black';
// stroked just for the demo.
// you don't have to stroke() if all you're doing is 'isPointInPath'
ctx.stroke();
}
function drawShield(cx, cy, r, startAngle, strokeWidth) {
ctx.beginPath();
ctx.arc(cx, cy, r, startAngle, startAngle + Math.PI);
ctx.lineWidth = strokeWidth;
ctx.strokeStyle = 'blue';
ctx.stroke();
}
function drawEnemy(cx, cy, r, fill) {
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.fillStyle = fill;
ctx.fill();
}
function handleMouseMove(e) {
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
ctx.clearRect(0, 0, cw, ch);
drawShield(cx, cy, radius, startAngle, shieldStrokeWidth);
defineShieldHitPath(cx, cy, radius, enemyRadius, startAngle);
if (ctx.isPointInPath(mouseX, mouseY)) {
drawEnemy(mouseX, mouseY, enemyRadius, 'red');
} else {
drawEnemy(mouseX, mouseY, enemyRadius, 'green');
}
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>The shield is the blue arc.<br>The filled circle that moves with the mouse is the enemy.<br>The black stroked arc is the shield perimiter.<br>The enemy turns red when colliding with the blue shield.<br>Test by moving the mouse-enemy in / out of the shield perimiter.</h4>
<canvas id="canvas" width=400 height=400></canvas>