HTML
<!DOCTYPE html>
<html>
<head>
<title>Canvas and SVG Example</title>
<style>
canvas {
border: 1px solid black;
}
svg {
border: 1px solid black;
}
</style>
</head>
<body>
<h2>Canvas</h2>
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(50, 50, 100, 100);
</script>
<h2>SVG</h2>
<svg width="200" height="200">
<rect x="50" y="50" width="100" height="100" fill="blue" />
</svg>
</body>
</html>
Code Output
HTML Canvas and SVG
HTML Canvas and SVG (Scalable Vector Graphics) are two different approaches to creating graphics and animations on the web.
HTML Canvas:
-
- The HTML
<canvas>
element provides a drawing surface on which you can use JavaScript to render graphics, animations, and interactive elements. - It offers a bitmap-based approach where you can directly manipulate individual pixels on the canvas.
- With the canvas API, you can draw various shapes, lines, text, and images, apply transformations, and create animations.
- The canvas is suitable for rendering dynamic and complex graphics, such as games, data visualizations, and real-time animations.
- As the canvas is pixel-based, resizing it may result in distortion if not handled properly.
<code><span></span>
- The HTML
SVG (Scalable Vector Graphics):
-
- SVG is an XML-based markup language for creating vector graphics that can be scaled and resized without losing quality.
- SVG graphics are resolution-independent, meaning they can be rendered at any size without pixelation.
- Instead of working with individual pixels, SVG uses mathematical descriptions to define shapes, lines, curves, and text.
- SVG elements can be styled and manipulated using CSS and animated using JavaScript or SMIL (Synchronized Multimedia Integration Language).
- SVG is well-suited for static and interactive graphics, icons, logos, and illustrations.
- It is also accessible and search engine-friendly due to its semantic structure.