简体   繁体   中英

Drawing .svg with javascript module "RDKIT-JS"

first of all I'm relatively new to javascript. So I'm sorry if my question is dumb. I would like to draw a molecule on my webiste by using this tool https://github.com/rdkit/rdkit-js . I also found an example here https://iwatobipen.wordpress.com/2021/12/29/create-desktop-chemoinformatics-application-with-js-chemoinformatics-rdkit-js/comment-page-1/ . This example works in my case but when i try to invoke a function to draw a molecule as a.svg without using the example code, I fail. I get this error-message in my browser:

Uncaught ReferenceError: RDKit is not defined
    at drawmol (results:21:15)
    at results:33:5

In the following code example you can see the first case where it works and the second case were it doesn't. In both cases i use the same function.:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://unpkg.com/@rdkit/rdkit/dist/RDKit_minimal.js"></script>
  <title>Document</title>
  <script>
    window
      .initRDKitModule()
      .then(function (RDKit) {
        console.log("RDKit version: " + RDKit.version());
        window.RDKit = RDKit;
      })
      .catch(() => {
      });
  </script>

  <script> var drawmol = function() {

    var mol = RDKit.get_mol("C1=CC=C(C=C1)O"); // the string here is a string representation of chemical molecules, it could also be something like "CO" or "CCCCC", shouldnt be important
    var svg = mol.get_svg();
    document.getElementById("drawer").innerHTML = svg;         
};
</script>
</head>

<body>
  <button type='button' onclick='drawmol()'> <!-- this works --> 
    draw 
  </button><br>  
  <script>
    // drawmol() //this doesnt work
  </script>

<div id='drawer'></div>
</body>

</body>
</html>

Later i would like to use the module to dynamically make those images. I use django as the framework. In this case i tried to present a minimal example without the django stuff.

Thanks in advance for your effort!

You are calling drawmol() before RDKit is ready.

To fix this, place it after RDKit is loaded:

    window
      .initRDKitModule()
      .then(function (RDKit) {
        console.log("RDKit version: " + RDKit.version());
        window.RDKit = RDKit;
        //Now RDKit is loaded you can safely call drawmol()
        drawmol();
      })
      .catch(() => {
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM