by Daniil Suleiman
<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
Lines
Line Properties
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);
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();
Circles and arcs
0
Pi
0.5Pi
1.5Pi
for( ; ; ) +
canvas methods (beginPath(), moveTo(), lineTo(), fill() and else)
+ some MAGIC..
Curves
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 Animations
clear the canvas
save the canvas state
Animation steps
(clearRect())
Scheduled updates
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);
by Daniil Suleiman