Core JavaScript

SVG - A Simple Example

The acronymSVG stands for Scalable Vector Graphics and refers to graphics that are generated by a geometric specification rather than by pixels, like an image (called rasterized graphics as opposed to the vectorized graphics described here).

The program below fetches the body element first. Then a div element is created and assigned the name qMainDiv. An image is then placed inside this div, an example of rasterized graphics.

After that, an svg element is created with a call to createElementNS(). Notice that this is different from the call to createElement() that we used to create the first div. We must always use createElementNS() to create SVG elements. Next, we create a circle and a cross as vector graphics, which have opacity .75 due to the opacity setting on the svg tag. Finally, we put all of the elements together at the end.

ASimpleSVGExample.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="ASimpleSVGExample.js"></script>
</body>
</html>

ASimpleSVGExample.js

var qBody = document.getElementsByTagName("body")[0];

var qMainDiv = document.createElement("div");
qMainDiv.style.backgroundImage = "url('hill_and_blue_sky.jpg')";
qMainDiv.style.width="400px";
qMainDiv.style.height="300px";

var qSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
qSvg.setAttribute('opacity', '.75');
qSvg.style.width="400px";
qSvg.style.height="300px";

var qCircle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
qCircle.setAttribute('cx', '200');
qCircle.setAttribute('cy', '150');
qCircle.setAttribute('r', '50');
qCircle.setAttribute('fill', 'rgb(255, 255, 100)');
qCircle.setAttribute('stroke-width', '3');
qCircle.setAttribute('stroke', 'rgb(255, 255, 255)');

var qPolyline = document.createElementNS("http://www.w3.org/2000/svg", "polyline")
var dCX = 200;
var dCY = 150;
var dWidth = 25;
var qCoord =
	(dCX-.5*dWidth) + " " + (dCY-2.5*dWidth) + " " +
	(dCX-.5*dWidth) + " " + (dCY-.5*dWidth) + " " +
	(dCX-2.5*dWidth) + " " + (dCY-.5*dWidth) + " " +
	(dCX-2.5*dWidth) + " " + (dCY+.5*dWidth) + " " +
	(dCX-.5*dWidth) + " " + (dCY+.5*dWidth) + " " +
	(dCX-.5*dWidth) + " " + (dCY+4.5*dWidth) + " " +
	(dCX+.5*dWidth) + " " + (dCY+4.5*dWidth) + " " +
	(dCX+.5*dWidth) + " " + (dCY+.5*dWidth) + " " +
	(dCX+2.5*dWidth) + " " + (dCY+.5*dWidth) + " " +
	(dCX+2.5*dWidth) + " " + (dCY-.5*dWidth) + " " +
	(dCX+.5*dWidth) + " " + (dCY-.5*dWidth) + " " +
	(dCX+.5*dWidth) + " " + (dCY-2.5*dWidth) + " " +
	(dCX-.5*dWidth) + " " + (dCY-2.5*dWidth);
qPolyline.setAttribute('points', qCoord);
qPolyline.setAttribute('fill', 'rgb(150, 75, 0)');
qPolyline.setAttribute('stroke-width', '3');
qPolyline.setAttribute('stroke', 'rgb(0, 0, 0)');

qSvg.appendChild(qCircle);
qSvg.appendChild(qPolyline);
qMainDiv.appendChild(qSvg);
qBody.appendChild(qMainDiv);
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.