Skip to main content
Chemistry LibreTexts

6.7: Rendering Chemical Structures with RDKit

  • Page ID
    555729
  • ​

    ​

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\ket}[1]{\left| #1 \right>}\)
    \(\newcommand{\bra}[1]{\left< #1 \right|}\)
    \(\newcommand{\braket}[2]{\left< #1 \vphantom{#2} \right| \left. #2 \vphantom{#1} \right>}\)
    \(\newcommand{\braopket}[3]{\left< #1 \vphantom{#2}\vphantom{#3} \right| #2 \vphantom{#1}\vphantom{#3} \left| #3 \vphantom{#1}\vphantom{#2} \right>}\)
    \(\newcommand{\qmvec}[1]{\mathbf{\vec{#1}}}\)
    \(\newcommand{\op}[1]{\hat{\mathbf{#1}}}\)
    \(\newcommand{\expect}[1]{\langle #1 \rangle}\)
    \(\newcommand{\dfn}[1]{\emph{\textbf{#1}}}\)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)

    This page explains how to render publication-quality chemical structures in WeBWorK problems using RDKit.js and SMILES strings. Students see interactive, consistent molecular drawings without any image files to manage.

    Use this page when: you want to display chemical structures such as amino acids, nucleotides, or peptides in a PGML problem. RDKit.js is loaded via HEADER_TEXT (see Common PG Macros for macro loading conventions). For common RDKit rendering errors, see Common Mistakes and How to Fix Them.

    Why RDKit.js instead of static images

    • High-quality, consistent rendering across all molecules and devices.
    • No image file management or hosting required.
    • SMILES strings are compact and easy to maintain in PG code.
    • Customizable rendering options (explicit hydrogens, stereochemistry labels, legends).
    • Students cannot reverse-image-search for answers.

    RDKit.js loads from a public CDN and runs entirely in the browser. It requires an internet connection and a modern browser with JavaScript enabled.

    Quick start pattern

    Every RDKit problem follows three steps: define a SMILES string, create an HTML canvas element, and load RDKit.js through HEADER_TEXT. Below is a minimal working example that displays L-alanine.

    Step 1: Define SMILES and create a canvas

    # ----------------------------
    # 2) Setup
    # ----------------------------
    
    # SMILES for L-alanine (zwitterion at physiological pH)
    $smiles_alanine = 'C[C@@H](C(=O)[O-])[NH3+]';
    
    # Build the canvas element with a unique id
    $canvas_alanine = '<canvas id="canvas_alanine" width="320" height="240"'
        . ' data-smiles="' . $smiles_alanine . '"></canvas>';
    

    Step 2: Load RDKit.js in HEADER_TEXT

    Place this block after loadMacros but before BEGIN_PGML. The JavaScript finds every canvas that has a data-smiles attribute and draws the corresponding molecule.

    HEADER_TEXT(<<'END_HEADER');
    <script src="https://unpkg.com/@rdkit/rdkit/dist/RDKit_minimal.js"></script>
    <script>
    let RDKitReady = null;
    function getRDKit() {
        if (!RDKitReady) {
            RDKitReady = initRDKitModule();
        }
        return RDKitReady;
    }
    function initMoleculeCanvases() {
        getRDKit().then(function(RDKit) {
            const canvases = document.querySelectorAll('canvas[data-smiles]');
            canvases.forEach((canvas) => {
                const smiles = canvas.dataset.smiles;
                if (!smiles) { return; }
                const mol = RDKit.get_mol(smiles);
                const mdetails = {
                    "legend": "",
                    "explicitMethyl": true
                };
                if (canvas && mol) {
                    mol.draw_to_canvas_with_highlights(
                        canvas, JSON.stringify(mdetails)
                    );
                    mol.delete();
                }
            });
        }).catch(error => {
            console.error('Error initializing RDKit:', error);
        });
    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initMoleculeCanvases);
    } else {
        initMoleculeCanvases();
    }
    </script>
    END_HEADER
    

    Step 3: Display the canvas in PGML

    BEGIN_PGML
    **Identify this amino acid:**
    
    [$canvas_alanine]*
    
    [_]{$answer}
    END_PGML
    

    The * after the closing bracket tells PGML not to escape the HTML, so the browser sees a real <canvas> element instead of literal tags.

    SMILES basics

    SMILES (Simplified Molecular Input Line Entry System) is a compact text notation for chemical structures. If you have never used SMILES before, the rules below are all you need for biochemistry problems.

    Atoms and bonds

    Atoms and bonds: feature, syntax, and example.
    Feature Syntax Example
    Standard atoms Uppercase letters: C, N, O, S, P CCO (ethanol)
    Single bond Implicit (omitted between atoms) CC (ethane)
    Double bond = C=O (formaldehyde core)
    Triple bond # C#N (cyanide)
    Branches Parentheses (...) for side chains CC(=O)O (acetic acid)
    Rings Matching digits to close a ring C1CCCCC1 (cyclohexane)
    Aromatic atoms Lowercase letters c1ccccc1 (benzene)

    Stereochemistry

    Many biological molecules are chiral. SMILES encodes chirality at tetrahedral centers with [C@@H] and [C@H], and double-bond geometry with / and \. For amino acids, the L-form typically uses [C@@H].

    # L-Alanine breakdown:
    #   C          methyl group (CH3)
    #   [C@@H]     chiral center (L-configuration)
    #   (C(=O)[O-])  carboxylate branch
    #   [NH3+]     protonated amino group
    
    $ala = 'C[C@@H](C(=O)[O-])[NH3+]';
    

    Charged species (critical for biochemistry)

    Most biological molecules carry formal charges at physiological pH. SMILES uses square brackets [...] for atoms with formal charges, explicit hydrogens, or non-default valence. Getting charges right is the single most common source of errors in biochemistry SMILES.

    Common ionizable groups

    Common ionizable groups: group, neutral form, charged form, and more.
    Group Neutral form Charged form SMILES (neutral) SMILES (charged)
    Carboxylic acid COOH COO- C(=O)O C(=O)[O-]
    Amino group NH2 NH3+ N [NH3+]
    Imidazole (His) NH + N NH + NH+ C1=CN=C([NH]1) C1=C([NH]C=[NH+]1)
    Guanidinium (Arg) C(=NH)(NH2)NH2 C(=NH2+)(NH2)NH2 C(=N)(N)N C(=[NH2+])(N)N
    Thiol (Cys) SH S- S [S-]
    Phenol (Tyr) OH O- O [O-]

    Critical note: imidazole protonation

    The imidazole ring on histidine is the most common source of SMILES errors. The protonated form has one hydrogen on each nitrogen (NH + NH+), not two hydrogens on one nitrogen. Using [NH2+] is incorrect for imidazole because that implies two hydrogens on a single nitrogen.

    # CORRECT: protonated histidine (pH below 6)
    # Imidazole ring has NH and NH+ (one H on each nitrogen)
    $his_protonated = 'C1=C([NH]C=[NH+]1)C[C@@H](C(=O)[O-])[NH3+]';
    
    # CORRECT: neutral histidine (pH above 6)
    # Imidazole ring has NH and N (hydrogen on only one nitrogen)
    $his_neutral = 'C1=CN=C([NH]1)C[C@@H](C(=O)[O-])[NH3+]';
    
    # WRONG: do not use NH2+ for protonated imidazole
    # $his_wrong = 'C1=C(N=C[NH2+]1)...';
    

    Validating SMILES strings

    Always validate every SMILES string before using it in a problem. An invalid SMILES will silently produce an empty canvas. Three methods are available, listed from most to least reliable.

    Method 1: Python RDKit (recommended)

    from rdkit import Chem
    
    smiles = "C[C@@H](C(=O)[O-])[NH3+]"
    mol = Chem.MolFromSmiles(smiles)
    
    if mol is None:
        print("ERROR: Invalid SMILES!")
    else:
        print(f"Valid SMILES")
        print(f"Formula: {Chem.rdMolDescriptors.CalcMolFormula(mol)}")
        print(f"Charge: {Chem.GetFormalCharge(mol)}")
    

    Method 2: Online SMILES viewers

    Paste a SMILES string into the PubChem Sketcher (https://pubchem.ncbi.nlm.nih.gov/edit3/index.html) or any other online SMILES viewer to see the rendered structure immediately.

    Method 3: Test render in WeBWorK

    Use the local renderer to preview the problem and confirm that the canvas draws the expected molecule.

    Canvas sizing guidelines

    The canvas dimensions control how large the structure appears. Choose a size based on molecule complexity.

    Canvas sizing guidelines: use case, width x height, aspect ratio, and more.
    Use case Width x Height Aspect ratio Examples
    Standard molecule 320 x 240 4:3 Single amino acids, monosaccharides
    Large molecule 480 x 320 3:2 Dipeptides, nucleotides, fatty acids
    Very large molecule 640 x 480 4:3 Tripeptides, complex lipids
    Compact (grid display) 240 x 180 4:3 Side-by-side comparisons

    Rendering options (mdetails)

    The mdetails object in the JavaScript controls how RDKit draws each molecule. Adjust these settings inside the HEADER_TEXT block.

    Production settings (for students)

    const mdetails = {
        "legend": "",
        "explicitMethyl": true
    };
    

    Debug settings (for development)

    const mdetails = {
        "legend": "Debug view",
        "explicitMethyl": true,
        "addAtomIndices": true,
        "addBondIndices": true,
        "addStereoAnnotation": true
    };
    
    Debug settings (for development): option, effect, and default.
    Option Effect Default
    legend Text label drawn below the molecule. ""
    explicitMethyl Shows CH3 groups as text rather than a bare vertex. true
    addAtomIndices Numbers each atom (useful for debugging). false
    addBondIndices Numbers each bond (useful for debugging). false
    addStereoAnnotation Draws R/S and E/Z labels on stereocenters. false

    Multiple molecules in one problem

    Pattern 1: Sequential display

    Create a separate canvas for each molecule. Each canvas must have a unique id.

    $smiles_ala = 'C[C@@H](C(=O)[O-])[NH3+]';
    $smiles_gly = 'C(C(=O)[O-])[NH3+]';
    
    $canvas_ala = '<canvas id="canvas_ala" width="320" height="240"'
        . ' data-smiles="' . $smiles_ala . '"></canvas>';
    $canvas_gly = '<canvas id="canvas_gly" width="320" height="240"'
        . ' data-smiles="' . $smiles_gly . '"></canvas>';
    
    BEGIN_PGML
    **Molecule A:**
    [$canvas_ala]*
    
    **Molecule B:**
    [$canvas_gly]*
    
    Which molecule is glycine? [_]{$answer}
    END_PGML
    

    Pattern 2: Side-by-side with HTML wrapper

    Wrap multiple canvases in a flex container to display them in a row.

    $side_by_side = '<div style="display: flex; gap: 1em;">'
        . '<div>' . $canvas_ala . '<p>Molecule A</p></div>'
        . '<div>' . $canvas_gly . '<p>Molecule B</p></div>'
        . '</div>';
    
    BEGIN_PGML
    Compare these molecules:
    
    [$side_by_side]*
    
    Which is glycine? [_]{$answer}
    END_PGML
    

    Randomization with RDKit

    Use a Perl hash to map molecule names to SMILES strings, then randomly select one. Always sort the hash keys before random selection so the same problem seed produces the same molecule.

    %amino_acids = (
        'alanine' => 'C[C@@H](C(=O)[O-])[NH3+]',
        'glycine' => 'C(C(=O)[O-])[NH3+]',
        'serine'  => 'C([C@@H](C(=O)[O-])[NH3+])O',
    );
    
    # Sort keys before random selection for seed stability
    @aa_names = sort keys %amino_acids;
    $selected_name = list_random(@aa_names);
    $selected_smiles = $amino_acids{$selected_name};
    
    $canvas = '<canvas id="canvas_aa" width="320" height="240"'
        . ' data-smiles="' . $selected_smiles . '"></canvas>';
    
    BEGIN_PGML
    Identify this amino acid:
    
    [$canvas]*
    
    [_]{$selected_name}
    END_PGML
    

    Why sort the keys? Perl hashes have no guaranteed ordering. Without sorting, the same seed could map to different molecules on different runs or different servers, making grades unreproducible.

    Common pitfalls

    1. Incorrect formal charges

    # WRONG: missing brackets around charged atom
    $smiles = 'CC(C(=O)O)NH3+';
    
    # RIGHT: square brackets enclose charged atoms
    $smiles = 'CC(C(=O)O)[NH3+]';
    

    2. Imidazole protonation errors

    # WRONG: NH2+ implies two H on one nitrogen
    $his = 'C1=C(N=C[NH2+]1)...';
    
    # RIGHT: NH and NH+ (one H on each nitrogen)
    $his = 'C1=C([NH]C=[NH+]1)...';
    

    3. Quote escaping in canvas attributes

    # WRONG: nested double quotes break the HTML attribute
    $canvas = "<canvas data-smiles=\"$smiles\"></canvas>";
    
    # RIGHT: use single-quoted string with dot concatenation
    $canvas = '<canvas data-smiles="' . $smiles . '"></canvas>';
    

    4. Canvas ID collisions

    # WRONG: duplicate IDs cause only one molecule to render
    $canvas1 = '<canvas id="canvas" ...></canvas>';
    $canvas2 = '<canvas id="canvas" ...></canvas>';
    
    # RIGHT: every canvas gets a unique ID
    $canvas1 = '<canvas id="canvas_mol1" ...></canvas>';
    $canvas2 = '<canvas id="canvas_mol2" ...></canvas>';
    

    5. Missing asterisk in PGML

    # WRONG: PGML escapes the HTML tags
    [$canvas]
    
    # RIGHT: the * tells PGML to output raw HTML
    [$canvas]*
    

    Chemistry-specific guidelines

    Amino acids

    At physiological pH (around 7.4), amino acids exist as zwitterions with a protonated amino group ([NH3+]) and a deprotonated carboxylate (C(=O)[O-]). Side chains may carry additional charges depending on their pKa.

    # L-Alanine (simple zwitterion)
    $ala = 'C[C@@H](C(=O)[O-])[NH3+]';
    
    # L-Lysine (charged side chain: extra NH3+)
    $lys = 'C(CC[NH3+])[C@@H](C(=O)[O-])[NH3+]';
    
    # L-Aspartate (charged side chain: extra COO-)
    $asp = 'C([C@@H](C(=O)[O-])[NH3+])C(=O)[O-]';
    
    # L-Histidine (protonated imidazole side chain)
    $his = 'C1=C([NH]C=[NH+]1)C[C@@H](C(=O)[O-])[NH3+]';
    

    Nucleotides and nucleobases

    # Adenine (neutral nucleobase)
    $adenine = 'C1=NC(=C2C(=N1)N=CN2)N';
    
    # Cytosine (neutral nucleobase)
    $cytosine = 'C1=CN(C(=O)N=C1N)C';
    

    Peptides

    # Dipeptide: Gly-Ala (peptide bond connects the two residues)
    $gly_ala = 'C[C@@H](C(=O)O)NC(=O)CN';
    

    Use a larger canvas (480 x 320 or larger) for peptides because the extended backbone needs more horizontal space.

    Troubleshooting

    Canvas shows an empty box

    • RDKit.js may not have loaded. Open the browser console and look for network errors.
    • Confirm that the WeBWorK server allows loading external scripts from the CDN.
    • Verify that HEADER_TEXT appears after loadMacros and before BEGIN_PGML.

    Console shows "Error initializing RDKit"

    • The SMILES string is probably invalid. Validate it with Python RDKit first.
    • Check that the data-smiles attribute is properly quoted (no nested double quotes).
    • Confirm that every canvas has a unique id.

    Molecule renders but looks wrong

    • Check stereochemistry: [C@@H] vs [C@H] changes the 3D arrangement.
    • Check formal charges: [NH3+] vs N changes protonation.
    • Check explicit hydrogens on charged atoms: [NH+] vs [N+].
    • Check ring closures: mismatched numbers produce the wrong ring system.

    Best practices checklist

    • Validate all SMILES with Python RDKit or an online viewer before publishing.
    • Use correct formal charges, especially [NH3+], [O-], and [NH+].
    • Give every canvas a unique id.
    • Choose canvas dimensions appropriate for the molecule complexity.
    • Sort hash keys before random selection for seed stability.
    • Use [$variable]* (with the asterisk) in PGML for HTML variables.
    • Test the rendered output in a browser before assigning to students.
    • Use production mdetails settings for student-facing problems.

    Complete working example

    Amino acid identification with RDKit -- A full problem that renders an amino acid structure using RDKit.js and asks students to identify it with RadioButtons.

    ## TITLE('Identify an amino acid from its structure')
    ## DESCRIPTION
    ## A chemical structure is rendered using RDKit.js. Students
    ## identify the amino acid from its structure.
    ## ENDDESCRIPTION
    ## KEYWORDS('amino acids','RDKit','chemical structure','RadioButtons')
    ## DBsubject('Biochemistry')
    ## DBchapter('Amino Acids')
    ## DBsection('Structure')
    ## Date('2026-02-15')
    ## Author('Author name')
    ## Institution('Institution name')
    
    DOCUMENT();
    loadMacros(
    	"PGstandard.pl",
    	"PGML.pl",
    	"parserRadioButtons.pl",
    	"PGcourse.pl",
    );
    
    HEADER_TEXT(<<'END_HEADER');
    <script src="https://unpkg.com/@rdkit/rdkit/dist/RDKit_minimal.js"></script>
    <script>
    let RDKitReady = null;
    function getRDKit() {
        if (!RDKitReady) { RDKitReady = initRDKitModule(); }
        return RDKitReady;
    }
    function initMoleculeCanvases() {
        getRDKit().then(function(RDKit) {
            const canvases = document.querySelectorAll('canvas[data-smiles]');
            canvases.forEach((canvas) => {
                const smiles = canvas.dataset.smiles;
                if (!smiles) { return; }
                const mol = RDKit.get_mol(smiles);
                const mdetails = {"legend": "", "explicitMethyl": true};
                if (canvas && mol) {
                    mol.draw_to_canvas_with_highlights(
                        canvas, JSON.stringify(mdetails));
                    mol.delete();
                }
            });
        }).catch(error => {
            console.error('Error initializing RDKit:', error);
        });
    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initMoleculeCanvases);
    } else {
        initMoleculeCanvases();
    }
    </script>
    END_HEADER
    
    $smiles = 'C[C@@H](C(=O)[O-])[NH3+]';
    $canvas = '<canvas id="canvas_aa" width="320" height="240"'
        . ' data-smiles="' . $smiles . '"></canvas>';
    
    $rb = RadioButtons(
    	[ 'Alanine', 'Glycine', 'Valine', 'Serine' ],
    	'Alanine',
    	labels        => 'ABC',
    	displayLabels => 1,
    );
    
    BEGIN_PGML
    Identify the amino acid shown below.
    
    [$canvas]*
    
    [_]{$rb}
    END_PGML
    
    ENDDOCUMENT();
    

    Apply it today

    • Copy the quick start pattern above into a new PG file and replace the SMILES string with your target molecule.
    • Validate the SMILES, set the canvas size, and preview in a browser.
    • For problems that compare multiple structures, give each canvas a unique ID and consider side-by-side layout.

    This page titled 6.7: Rendering Chemical Structures with RDKit was last modified on Fri, 27 Feb 2026 15:35:48 GMT and is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Neil R. Voss.