Skip to content

Instantly share code, notes, and snippets.

@codeincontext
Created August 26, 2012 19:05
Show Gist options
  • Select an option

  • Save codeincontext/3482669 to your computer and use it in GitHub Desktop.

Select an option

Save codeincontext/3482669 to your computer and use it in GitHub Desktop.
canvas demo
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<h1>canvas</h1>
<canvas width="400" height="400" id="canvasElement"></canvas>
<script type="text/javascript">
var ctx = canvasElement.getContext('2d');
var speedX = 2;
var speedY = 3;
var currentX = 100;
var currentY = 350;
function drawAtXY(x,y) {
ctx.clearRect(0,0,400,400)
ctx.fillStyle = 'red';
ctx.fillRect(x,y,30,30);
}
function redraw() {
currentX += speedX;
currentY += speedY;
drawAtXY(currentX, currentY);
if (currentX > 370) speedX = -2;
if (currentX < 0) speedX = 2;
if (currentY > 370) speedY = -3;
if (currentY < 0) speedY = 3;
}
setInterval(redraw,30);
$(canvasElement).on('click', checkClick);
function checkClick(event) {
var x = event.offsetX;
var y = event.offsetY;
console.log('there was a click at x: '+x+' y: '+y);
var rightOfBox = currentX+30
var bottomOfBox = currentY+30
if (x > currentX && x < rightOfBox) {
if (y > currentY && y < bottomOfBox) {
alert('hit')
}
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment