HTML and CSS Reference
In-Depth Information
You're probably thinking it looks familiar, and you're right. Many of
the things that can be achieved with
<canvas>
can also be easily
achieved with
SVG
. You'll learn more about the relative strengths and
weaknesses of each in the section “
SVG
vs. <canvas>,” but for now all
you need to understand is that
<canvas>
and
SVG
are based on different
conceptual models of how to create images.
<canvas>
is what program-
mers call
imperative
; you provide a detailed list of operations to be per-
formed that will produce a particular result.
SVG
is
declarative
; you
provide a description of the final result and let the browser get on with
it. Where
<canvas>
requires JavaScript,
SVG
requires markup, much
like
HTML
, and it can be included directly in
HTML5
:
<!DOCTYPE html>
<html>
<head>
<title>SVG example 2</title>
</head>
<body>
<svg id="mysvg" viewBox="0 0 320 240"
style="outline: 1px solid #999; width: 320px; height:
240px;">
<rect x="50" y="50" width="100" height="100"
style="fill: rgb(255,0,0)">
</rect>
<line x1="50" y1="50" x2="150" y2="150"
style="stroke: rgb(0,127,127); stroke-width: 5;">
</line>
</svg>
</body>
</html>
There are several interesting things to be seen in this simple example.
First, note that the size of the element on the page is determined by
CSS
in the
style
attribute, but you also define a
viewBox
with the same
values. Because
SVG
is a vector format, pixels aren't as significant; you
can use
viewBox
to define a mapping between the physical dimensions of
the element, defined in
CSS
, and the logical coordinates of everything
displayed within.