Beispiel:SVG-script-3.html
Aus SELFHTML-Wiki
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" media="screen" href="./Beispiel:Grundlayout.css">
<style>
svg {
height: 410px;
border: thin solid;
--bgcolor: #e6f2f7;
--blue: #337799;
--yellow: #dfac20;
--green: #8db243;
--accent: #c82f04;
}
#text {
font-size: 24px;
font-weight: bold;
text-anchor: middle;
}
ellipse {
fill-opacity: .5;
stroke: black;
stroke-width: .5;
cursor: pointer;
}
#createButton {
fill: #5a9900;
fill-opacity: .5;
stroke: black;
stroke-width: 1;
cursor: pointer;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function () {
var count = 0, // Zählvariable für id + Farben-array
colors = new Array( 'red', 'orange', 'yellow', 'lime', 'skyblue', 'hotpink'),
svg = document.querySelector('svg');
//Beispiel: svg.appendChild( getNode('ellipse', { cx:200, cy:250, rx:20, ry:50, fill:'lime' }) );
function createEllipse(){
svg.appendChild( getNode('ellipse', {
id: 'ellipse' + count,
cx: rand(0,880),
cy: rand(0,400),
rx: 30,
ry: 20,
fill: colors[rand(0, colors.length-1)]
}) );
count++;
}
function removeEllipse(event) {
var elem = event.target;
if ('rect' != elem.nodeName) {
var parent = elem.parentNode;
parent.removeChild(elem);
}
}
function getNode(elem, v) {
elem = document.createElementNS("http://www.w3.org/2000/svg", elem);
for (var p in v)
elem.setAttribute(p, v[p]);
return elem;
}
function rand (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
document.querySelector('#createButton').addEventListener('click', createEllipse);
document.querySelector('svg').addEventListener('click', removeEllipse);
});
</script>
<title>SVG und JavaScript 3</title>
</head>
<body>
<h1>SVG und JavaScript - <br>Ellipsen erzeugen und löschen</h1>
<svg viewBox="0 0 880 450">
<text x="60" y="420">Erzeuge Ellipse!</text>
<rect id="createButton" tabindex="1" x="50" y="400" width="150" height="30" rx="5" />
</svg>
</body>
</html>