Skip to content

Instantly share code, notes, and snippets.

@toddbranch
Last active December 2, 2016 19:01
Show Gist options
  • Save toddbranch/c89fd1afa8496beb753badce1da3f54c to your computer and use it in GitHub Desktop.
Save toddbranch/c89fd1afa8496beb753badce1da3f54c to your computer and use it in GitHub Desktop.
// 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