library(minisvg)

Add Javascript code for a <script> block

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Create a document with a single blue rectangle
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
doc <- svg_doc(width = 200, height = 200)
doc$rect(
  id     = "myrect",
  x      = 10,
  y      = 10,
  width  = 180,
  height = 180,
  fill   = 'blue'
)

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Add javascript to edit the DOM and change the fill colour to blue
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
doc$add_js_code("
var element = document.getElementById('myrect');
element.setAttributeNS(null, 'fill', 'green');
console.log('hi {minisvg}');
")

doc$save("svg/javascript-01.svg")
  <?xml version="1.0" encoding="UTF-8"?>
  <svg width="200" height="200" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <rect id="myrect" fill="blue" x="10" y="10" width="180" height="180" />
  <script language='javascript'>
  <![CDATA[
  
  var element = document.getElementById('myrect');
  element.setAttributeNS(null, 'fill', 'green');
  console.log('hi {minisvg}');
  
  ]]>
  </script>
  </svg>