jh75t
jh75t

Reputation: 3

JavaScript function to draw SVG elements

Hello I would like to write a simple function that creates circles where I only have to specify the x, y coordinates.

JavaScript code is:

function cir(x, y){
    <circle cx="x" cy="y" r="10" fill="blue" />;
}

HTML code is:

<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
</head>

<body>

  <svg width="1024" height="768">

    cir(50, 50);

    </svg>

</body>

</html>

What am I doing wrong?

Upvotes: 0

Views: 423

Answers (1)

Andy
Andy

Reputation: 63587

You can return some HTML using a template literal and add it to your SVG element.

function cir(x, y) {
  return `<circle cx=${x} cy=${y} r="10" fill="blue" />`;
}

document.querySelector('svg').insertAdjacentHTML('beforeend', cir(50, 50));
<svg width="1024" height="768"></svg>

Note: you should move your script to just before your </body> tag. That way the document will have time to load before the script is executed.

  <script src="script.js"></script>
</body>

DOM resources on MDN:

EDIT

Now, if you wanted to include a form from which you can get the coordinates, you can do something like this.

function cir(x, y) {
  return `<circle cx=${x} cy=${y} r="10" fill="blue" />`;
}

// Grab all the elements
const button = document.querySelector('.submit');
const svg = document.querySelector('svg');
const x = document.querySelector('.x');
const y = document.querySelector('.y');

// Add an event listener to the button
button.addEventListener('click', addShape, false);

function addShape(e) {

  // Prevent the form from submitting
  e.preventDefault();
  svg.insertAdjacentHTML('beforeend', cir(x.value, y.value));
}
<form>
 <input class="x" type="text" placeholder="X coord" />
 <input class="y" type="text" placeholder="Y coord" />
 <button class="submit">Submit</button>
</form>
<svg width="1024" height="768"></svg>

You can add more inputs for the radius and colour if you wanted.

Upvotes: 3

Related Questions