Last active
December 2, 2016 19:01
-
-
Save toddbranch/c89fd1afa8496beb753badce1da3f54c 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
// Extended drawing example where we change colors on mouse click. | |
<canvas id="myCanvas" width="400" height="400"></canvas> | |
<script> | |
var canvas = document.getElementById('myCanvas'); | |
var context = canvas.getContext('2d'); | |
// array of colors to rotate through on click | |
var colors = [ | |
'red', | |
'blue', | |
'yellow', | |
'green', | |
'purple', | |
'white' | |
]; | |
// which color are we on? | |
var colorIndex = 0; | |
// only run this function when the mouse button goes down | |
canvas.addEventListener('mousedown', function() { | |
// go to the next color | |
colorIndex++; | |
// have we gone past the end of the array? if yes, start over | |
if (colorIndex >= colors.length) { | |
colorIndex = 0; | |
} | |
}); | |
canvas.addEventListener('mousemove', function(event) { | |
// set the fill style to our current color | |
context.fillStyle = colors[colorIndex]; | |
context.fillRect(event.x, event.y, 10, 10); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment