canvas

Drawing pictures with code

Room name: jkohlin

the HTML element

The canvas element is just an empty container with a width and a height. 

<canvas width="300" height="150" id="myCanvas">

  I'm sorry about your browser, it's not very good.
  But hey, they got new ones at google.com/chrome.
  <img src="images/sad_emoji.png" alt="">

</canvas>

canvas drawing context

<canvas width="300" height="150" id="myCanvas">

  I'm sorry about your browser, it's not very good.
  But hey, they got new ones at google.com/chrome.
  <img src="images/sad_emoji.png" alt="">

</canvas>

HTML

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;

JavaScript

canvas {
    background-image: url(game_bg.png);
    background-size: cover;
}

CSS

Drawing rectangles

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d"); // ctx is shorter than context...
var w = canvas.width;
var h = canvas.height;

// ctx.fillRect(startX, startY, width, height)
ctx.fillRect(0, 0, 100, 50);

ctx.strokeRect(w/2, h/2, 50, 75);

Styling

// ctx is the canvas.getContext("2d")
ctx.fillStyle = color - change fill color
ctx.strokeStyle = color - change stroke color
ctx.lineWidth = number - width in pixels

ctx.lineCap = "butt" / "round" / "square" 
ctx.lineJoin = "miter" / "bevel" / "round" -corners
ctx.miterLimit = integer - higher numbers allow sharper corners


ctx.save() saves the current stroke and color state
ctx.restore() resets any changes made to stroke and color, to last saved state

Styling

// ctx is the canvas.getContext("2d")
ctx.fillStyle = color - change fill color
ctx.strokeStyle = color - change stroke color
ctx.lineWidth = number - width in pixels

ctx.lineCap = "butt" / "round" / "square" 
ctx.lineJoin = "miter" / "bevel" / "round" -corners
ctx.miterLimit = integer - higher numbers allow sharper corners


ctx.save() saves the current stroke and color state
ctx.restore() resets any changes made to stroke and color, to last saved state

lines

 ctx.moveTo(startX,startY); 
 ctx.lineTo(endX,endY); 
 ctx.closePath(); 
 ctx.stroke(); 
 ctx.fill();  

circles


beginPath() //starts drawing a a path.
arc(startX, startY, radius, startAngle, endAngle) 
//draws a circle where 2*Math.PI is the end angle in radians for a full circle
stroke() //adds a stroke to your shape
fill() //fills your shape

Save as image

var canvas = document.getElementById("myCanvas");

var img = canvas.toDataURL("image/png");

location.href = img;

animate

var canvas = document.getElementById("star");
var ctx = canvas.getContext("2d");
var x = 0;
var y = 0;
var w = canvas.width;
var h = canvas.height;

function update(){
    ctx.clearRect(0,0,w,h);
    ctx.fillRect(x,y, 20,20);
    x++; 
    y++;
    requestAnimationFrame(update)
}

update();

Canvas #1

By Johan Kohlin

Canvas #1

  • 795