Created
October 24, 2016 10:49
-
-
Save eirabben/9a68d9289fbd0ba1c29e83dbe2fff635 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var canvas = document.getElementById('canvas'); | |
var context = canvas.getContext('2d'); | |
// Rectangles | |
context.fillRect(100, 100, 50, 50); // x, y, width, height | |
context.strokeRect(300, 300, 50, 50); | |
// // Path | |
context.beginPath(); | |
context.moveTo(400, 100); // x, y | |
context.lineTo(500, 200); // x, y | |
context.lineTo(400, 200); | |
context.fill(); | |
context.beginPath(); | |
context.arc(600, 400, 40, 0, Math.PI * 2); // x, y, radius, startAngle, endAngle | |
context.stroke(); | |
// // Colors | |
context.fillStyle = 'red'; | |
context.strokeStyle = 'rgb(0, 200, 0)'; | |
context.fillRect(200, 100, 50, 50); | |
// // Text | |
context.font = '36px sans-serif'; | |
context.fillText('HTML Canvas!', 100, 500); // text, x, y | |
context.strokeText('HTML Canvas!', 500, 500); | |
var fox = new Image(); | |
fox.onload = function() { | |
context.drawImage(fox, 100, 100); // Image, x, y | |
}; | |
fox.src = 'fox.jpg'; | |
var flower = new Image(); | |
flower.onload = function() { | |
context.drawImage(flower, 100, 100); // Image, x, y | |
var imageData = context.getImageData(0, 0, canvas.width, canvas.height); // rect | |
// [red, green, blue, alpha, red, green, blue, alpha, red, green, blue, alpha, red, green, blue, alpha] | |
var data = imageData.data; | |
for (var i = 0; i < data.length; i +=4) { | |
var avg = (data[i] + data[i+1] + data[i+2]) / 3; | |
data[i] = avg; // red | |
data[i+1] = avg; // green | |
data[i+2] = avg; // blue | |
} | |
context.putImageData(imageData, 0, 0); | |
}; | |
flower.src = 'flower.jpg'; | |
// Animation | |
var x = 100; | |
var y = 100; | |
context.scale(1, 1); // x, y | |
function animate() { | |
// Erase everything on the canvas | |
context.clearRect(0, 0, canvas.width, canvas.height); | |
// Update variables | |
context.translate(150, 150); // x, y | |
context.rotate(0.1); | |
context.translate(-150, -150); | |
// Draw shapes | |
context.fillRect(x, y, 100, 100); | |
// Start next frame | |
window.requestAnimationFrame(animate); | |
} | |
// Start the first animation frame. | |
window.requestAnimationFrame(animate); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment