Skip to content

Instantly share code, notes, and snippets.

@NrupM
Last active September 11, 2017 18:28
Show Gist options
  • Save NrupM/f2bb9a39223ba3a69cb0aa094b74a731 to your computer and use it in GitHub Desktop.
Save NrupM/f2bb9a39223ba3a69cb0aa094b74a731 to your computer and use it in GitHub Desktop.
HTML5 canvas lightning talk

<canvas> is an HTML element used to draw graphics using scripts (usuallt JavaScript)

The HTML <canvas> element is only a container for graphics. Canvas has several methods for drawing paths, boxes, circles, text and for adding images.

Basic usage

The <canvas> element

  <canvas width='150' height='150'></canvas>
  <script src="canvas.js"></script>

The rendering context

The <canvas> element has a method called .getContext() used to access drawing functions

    const canvas = document.querySelector('canvas');
    let c = canvas.getContext('2d');
    c.fillRect(10, 10, 100, 100);
    c.fillStyle = 'green';

Drawing Shapes

The canvas has a default grid overlay, normally 1 unit in the grid cooresponds to 1 pixel on the canvas.
The position of each drawn item will be translate it's (x, y) coordinates to different posoitions on the grid.

Rectangles
fillRect(x, y, width, height Draws a filled rectangle.
Parameters x and y specify the position on the canvas, width and height provide the rectangle's size.

Paths
A path is a list of points, connected by segments of lines that can be curved, and have different widths and colors.
To make a shape using paths:

  1. Create the path.
  2. Use drawing commands to draw into the path.
  3. Close the path.
  4. Stroke or fill the path to render it.

c.beginPath() initializes the path.

moveTo(x, y) function to place the starting point.

lineTo(x, y) draws a line from the current position to the specified x and y postion.
The starting point is dependent on previously drawn paths, where the end point of the previous path is the starting point for the following, etc.

Arcs/Cirlces
Use the arc method

arc(x, y, radius, startAngle, endAnge, anticlockwise)
Draws an arc which is centered at (x,Y) with radius starting at startAngle and ending at endAngle going in the given direction.

Applying styles and colors

fillStyle = color
Sets the style used when filling shapes

strokeStyle = color
Sets the style for shapes outlines

Resources

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial
https://codepen.io/pen/?editors=1010
https://codepen.io/NrupM/pen/QqLwMN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment