Professional Documents
Culture Documents
HTML 5 Canvas & SVG
HTML 5 Canvas & SVG
HTML 5 Canvas & SVG
FE Developer
Love code, technology, sport
The HTML <canvas> element is SVG stands for Scalable Vector
used to draw graphics Graphics
The <canvas> element is only a The HTML <svg> element is a
container for graphics. You must container for SVG graphics.
use a script to actually draw the
graphics. SVG has several methods for
drawing paths, boxes, circles, text,
Canvas has several methods for and graphic images.
drawing paths, boxes, circles, text,
and adding images.
Canvas SVG
Script - Drawing via code Document - Drawing via XML
Rendered pixel by pixel Scalable Vector Graphics
Y
HTML
<canvas id="canvas">
This Browser Not Support
</canvas>
JS
var canvasElement = document.getElementById("canvas");
var canvas = canvasElement.getContext("2d");
canvas.font = "50px arial";
canvas.fillText("Hello World", 10, 50);// (text, x, y)
CSS
canvas{
border:1px solid;
width: 50%;
height: 50%
}
Paths
Method Description
fill() Fills the current drawing (path)
stroke() Actually draws the path you have defined
beginPath() Begins a path, or resets the current path
moveTo() Moves the path to the specified point in the canvas, without creating a
line
closePath() Creates a path from the current point back to the starting point
lineTo() Adds a new point and creates a line from that point to the last specified
point in the canvas
clip() Clips a region of any shape and size from the original canvas
quadraticCurveT Creates a quadratic Bézier curve
o()
bezierCurveTo() Creates a cubic Bézier curve
canvas.beginPath();
canvas.moveTo(10, 10);
canvas.lineTo(80, 10);
canvas.stroke();
canvas.beginPath();
canvas.moveTo(80, 10);
canvas.lineTo(80, 100);
canvas.stroke();
canvas.fillStyle="#0000FF";
canvas.fill();// Fills the current drawing (path)
canvas.lineWidth = 5;
canvas.strokeStyle = "#00FF00";
canvas.stroke(); //Actually draws the path you have defined
arc signature context.arc(centerX,centerY,radius,startAngle,endAngle,counterclockwise);
canvas.beginPath();
canvas.arc(centerX, centerY, radius, startAngle, endAngle);
canvas.stroke();
1 HTML Canvas element
1 moving arc
1 moving paddle (mouse\keyboard)
25 bricks colorful bricks
HTML
<svg height="200" width="200">
<text x="50" y="50" fill="red">Healow World</text>
Sorry, your browser does not support SVG.
</svg>
Result
HTML
<svg height="200" width="500">
<polyline points="20,20,100,20,100,120,200,120"
style="fill:none;stroke:red;stroke-width:3" />
</svg>
Result
HTML
<svg width="400" height="110">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
Sorry, your browser does not support SVG.
</svg>
Result
HTML
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="red" stroke-width="2" fill="blue" />
Sorry, your browser does not support SVG.
</svg>
Result