Johan Kohlin
Lecturer at School of engineering, Jönköping University.
Drawing pictures with code
Room name: jkohlin
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 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
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);
// 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
// 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
ctx.moveTo(startX,startY);
ctx.lineTo(endX,endY);
ctx.closePath();
ctx.stroke();
ctx.fill();
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
var canvas = document.getElementById("myCanvas");
var img = canvas.toDataURL("image/png");
location.href = img;
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();
By Johan Kohlin