Skip to content

Instantly share code, notes, and snippets.

@aresnick
Last active July 6, 2016 19:33
Show Gist options
  • Save aresnick/06774475f98f2aed76ef to your computer and use it in GitHub Desktop.
Save aresnick/06774475f98f2aed76ef to your computer and use it in GitHub Desktop.

A small example of drawing with canvas

In this sketch we put together a minimal example of drawing with the canvas API, adding the barest functionality of a simple paint program. You can find a screencast developing the sketch here.


Further doing

Modify the code so that:

  1. …each time you click down and then up, the pen color changes
  2. …when you click a button on screen, a triangle is inserted into the canvas
  3. …you have a small palette of colored divs which you can click on to select the color of the pen.

Further reading

<html>
<head>
<style>
#myCanvas {
border: 1px black dotted;
/* A bit of border so that we can see our canvas */
}
</style>
</head>
<body>
<canvas width='500px' height='500px' id='myCanvas'></canvas>
<script>
var canvas = document.querySelector('#myCanvas'); // Grab a JS hook into our canvas element
var ctx = canvas.getContext('2d'); // Grab the rendering context, which we actually use to draw
var line = function(x1, y1, x2, y2) { // A convenience function to draw a line between two points in our context
ctx.beginPath(); // start a path
ctx.moveTo(x1, y1); // move our pen to x1, y1
ctx.lineTo(x2, y2); // draw a line from wherever our pen is to x2, y2
ctx.stroke(); // and then actually fill in the line with whatever stroke is defined
ctx.closePath(); // and close our path
};
var mouseIsDown = false; // a variable we'll toggle to keep track of whether the mouse is down
var mousePosition = { // a convenience dictionary for storing our mouse's x- and y-coordinates
x: null,
y: null
};
var updateMousePosition = function(event) { // a function to take a MouseEvent and update our mousePosition dictionary with the right x- and y-coordinates from the MouseEvent
mousePosition.x = event.offsetX;
mousePosition.y = event.offsetY;
};
canvas.addEventListener('mousedown', function(event) { // When the mouse button is pressed down on the canvas element
mouseIsDown = true; // toggle mouseIsDown
updateMousePosition(event); // update the mousePosition
});
canvas.addEventListener('mouseup', function(event) { // When we release the mouse button on the canvas element
mouseIsDown = false; // toggle mouseIsDown
});
canvas.addEventListener('mousemove', function(event) { // When the mouse is moved over the canvas element
if (mouseIsDown) { // If the mouse button is also down (i.e. if we're dragging)
line(mousePosition.x, mousePosition.y, event.offsetX, event.offsetY); // draw a line from our old (mousePosition.x, .y) coordinates to the event's coordinates
updateMousePosition(event); // and then update our mousePosition coordinates
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment