HTML 5
<canvas>
by Daniil Suleiman
<canvas> can:
- Draw Graphics
- Draw Text
- Can be Animated
- Can be Interactive
- Can be used in Games


Draw on the Canvas With JavaScript
<script>
var canvas
...
</script>
getContext()
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
...
...
</script>
<body>
<canvas id="line"></canvas>
<script>
var line = document.getElementById("line");
var ctx = line.getContext("2d");
ctx.moveTo(0, 0);
ctx.strokeStyle = 'purple';
ctx.lineTo(300, 150);
ctx.stroke();
</script>

x
y
0
- moveTo(x, y)
- lineTo(x, y)
- stroke()
Lines
Line Properties
- lineCap
- lineJoin
- lineWidth



butt
round
square
1px
12px

var rectangle = document.getElementById('rectangle');
var ctx = rectangle.getContext('2d');
ctx.strokeStyle = 'green';
ctx.strokeRect(100, 25, 100, 100);
Rectangles

var rectangle = document.getElementById('rectangle');
var ctx = rectangle.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(100, 25, 100, 100);
- fillRect(x,y,width,height)
- strokeRect(x,y,width,height)

var circle = document.getElementById("circle");
var ctx = circle.getContext("2d");
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.arc(150, 75, 60, 0, 2*Math.PI);
ctx.stroke();
- beginPath()
- arc(x,y,radius, startAngle, endAngle)
Circles and arcs
0
Pi
0.5Pi
1.5Pi
for( ; ; ) +
canvas methods (beginPath(), moveTo(), lineTo(), fill() and else)
+ some MAGIC..
- quadraticCurveTo(cpx,cpy,x,y)
Curves
- bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y)

for( ; ; ) +
bezierCurveTo()
+ no MAGIC..

<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var grd=ctx.createRadialGradient(100,100,100,100,100,0);
grd.addColorStop(0,"white");
grd.addColorStop(1,"blue");
ctx.fillStyle = grd;
ctx.fillRect(0,0,200,200);
</script>

<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var grd=ctx.createLinearGradient(0,0,250,0);
grd.addColorStop(0,"blue");
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
ctx.fillRect(10,10,250,150);
</script>
Canvas - Gradients
- createLinearGradient()
- createRadialGradient()
That's what I've got
Canvas Animations

-
clear the canvas
-
save the canvas state
- draw animated shapes
- restore the canvas state
Animation steps
(clearRect())
- setInterval()
- setTimeout()
- requestAnimationFrame()
Scheduled updates

The Svisloch' river?!?!
Drawing Text on the Canvas

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.font = "90px Arial";
ctx.fillText("EPAM",50,100);

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.font = "90px Arial";
ctx.strokeText("EPAM",50,100);
- fillText(text,x,y)
- strokeText(text,x,y)

HTML 5
<canvas>
by Daniil Suleiman

HTML Canvas
By Daniel Suleiman
HTML Canvas
- 303