Skip to content

Instantly share code, notes, and snippets.

@eirabben
Created October 25, 2016 20:06
Show Gist options
  • Save eirabben/8321713f3f16b1fbc69fce6245229b70 to your computer and use it in GitHub Desktop.
Save eirabben/8321713f3f16b1fbc69fce6245229b70 to your computer and use it in GitHub Desktop.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// Animation
var animationFrame;
function animate() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = '#247ba0';
context.translate(350, 250);
context.rotate(0.05);
context.translate(-350, -250);
context.fillRect(300, 200, 100, 100);
animationFrame = window.requestAnimationFrame(animate);
}
window.requestAnimationFrame(animate);
canvas.onmouseover = function() {
animationFrame = window.requestAnimationFrame(animate);
}
canvas.onmouseleave = function() {
window.cancelAnimationFrame(animationFrame);
}
// Mouse input
var fox = new Image();
fox.onload = function() {
context.drawImage(fox, 200, 200);
};
fox.src = 'fox.jpg';
canvas.onmouseover = function() {
context.fillRect(300, 300, 100, 100);
};
canvas.onmouseleave = function() {
context.clearRect(0, 0, canvas.width, canvas.height);
};
canvas.onmousemove = function(event) {
var x = event.clientX;
var y = event.clientY;
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(x - 50, y - 50, 100, 100);
};
canvas.onclick = function(event) {
var x = event.clientX;
var y = event.clientY;
context.fillRect(x - 50, y - 50, 100, 100);
};
var drawing = false;
canvas.onmousedown = function(event) {
drawing = true;
}
canvas.onmouseup = function(event) {
drawing = false;
}
canvas.onmousemove = function(event) {
var x = event.clientX;
var y = event.clientY;
if (drawing == true) {
context.fillRect(x - 10, y - 10, 20, 20);
}
}
var x = 300;
var y = 300;
context.fillRect(x, y, 50, 50);
document.onkeydown = function(event) {
console.log(event);
if (event.key == 'ArrowRight') {
x += 5;
} else if (event.key == 'ArrowLeft') {
x -= 5;
} else if (event.key == 'ArrowUp') {
y -= 5;
} else if (event.key == 'ArrowDown') {
y += 5;
}
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(x, y, 50, 50);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment