Marvin JS Examples - Convert Structure To Image

Back to index

In this example, you can create PNG, JPEG or SVG picture from the given molecule source.

  • Carbon labels
  • CPK coloring
  • Show Stereo Info
  • Show chiral flag
  • Show Lone Pairs
  • Atom Indeces
  • Implicit Hydrogens
  • Display Mode
  • Zoom Mode
  • Width:
  • Height:
  • Background Color:
  • AUTO mol mrv smiles smarts

    Create a DIV element where the generated images will be embedded. It is hidden till the image is inserted.

    <div id="imageContainer" class="left10" style="display: none;">
      <img id="image" class="bordered" />
    </div>

    The following dependencies are used in this example:

    	<script src="../js/lib/jquery-1.9.1.min.js"></script>
    	<script src="../gui/lib/promise-1.0.0.min.js"></script>
    	<script src="../js/marvinjslauncher.js"></script>	
    	<script src="../js/webservices.js"></script>

    You need the marvin.ImageExporter class to convert structure to image. Loads this API into a separate iframe to avoid potential css conflicts.

    Use the marvinpack.html that loads the marvin namespace.
    		$(document).ready(function handleDocumentReady (e) {
    			// load marvin namespace in a separate frame to avoid css conflict
    			// the display attribute of this iframe cannot be "none", but you can hide it somewhere
    			$('body').append($('<iframe>', { id: "marvinjs-iframe", src: "../marvinpack.html"}));
    			// wait for the reference of marvin namespace from the iframe
    			MarvinJSUtil.getPackage("#marvinjs-iframe").then(function(marvinNameSpace) {
    				// the reference to the namespace is arrived but there is no guaranty that its initalization has been finished
    				// because of it, wait till the ready state to be sure the whole API is available
    				marvinNameSpace.onReady(function() {
    					marvin = marvinNameSpace;
    					initControl();
    				});	
    			}, function(error) {
    				alert("Cannot retrieve marvin instance from iframe:"+error);
    			});
    		});
    

    To hide the iframe, the following CSS settings are used:

    	iframe#marvinjs-iframe {
    		width: 0;
    		height: 0;
    		display: initial;
    		position: absolute;
    		left: -1000;
    		top: -1000;
    		margin: 0;
    		padding: 0;
    	}

    The initcontrol function bind click handler for the buttons.

    		function initControl() {
    			$("#molsource-box").val(source);
    			$("#createPNG").on("click", function() {
    				createImage("image/png", applyDataUri);
    			});
    			$("#createJPEG").on("click", function() {
    				createImage("image/jpeg", applyDataUri);
    			});
    			$("#createSVG").on("click", function() {
    				createImage("image/svg", applySvg);
    			});
    		}

    The createImage function creates a new instance of ImageExporter class and call its render function to convert the given string to image. It is an asynchrone exporter, the render function returns with a Promise instance. The given callback function processes the result of the image export. It is automatically evaluated when the export process is completed.

    		function createImage(imageType, callback) {
    			var exporter = createExporter(imageType);
    			exporter.render($("#molsource-box").val()).then(callback, alert);
    		}

    The createExporter function retrieves the current settings to create a new ImageExporter object with these settings.

    		function createExporter(imageType) {
    			var settings = {
    				'carbonLabelVisible' : $("#chbx-carbonVis").is(':checked'),
    				'cpkColoring' : $("#chbx-coloring").is(':checked'),
    				'chiralFlagVisible': $("#chbx-chiral").is(':checked'),
    				'lonePairsVisible' : $("#lonepairs").val() != '0',
    				'lonepaircalculationenabled' : $("#lonepairs").val() == '2',
    				'atomIndicesVisible': $("#chbx-atomIndeces").is(':checked'),
    				'implicitHydrogen' : $("#implicittype").val(),
    				'displayMode' : $("#displayMode").val(),
    				'background-color': $('#bg').val(),
    				'zoomMode' : $("#zoommode").val(),
    				'width' : parseInt($("#w").val(), 10),
    				'height' : parseInt($("#h").val(), 10)
    			};
    
    			var inputFormat = $("input[type='radio'][name='inputFormat']:checked").val();
    			if(inputFormat == "") {
    				inputFormat = null;
    			}
    			var defaultServices = getDefaultServices();
    			var services = {};
    			services['molconvertws'] = defaultServices['molconvertws'];
    			if($('#chbx-calcStereo').is(":checked")) {
    				services['stereoinfows'] = defaultServices['stereoinfows']; // enable stereo calculation
    			}
    			var params = {
    					'imageType': imageType, // type of output image
    					'settings': settings, // display settings
    					'inputFormat': inputFormat, // renderer will expect molecule source in this format
    					'services': services // to resolve any molecule format and be able to calculate stereo info
    			}
    			return new marvin.ImageExporter(params);
    		}

    At PNG and JPEG image generation, ImageExporter generates a base64 based data URI. To display it, create a new img tag and set the result string to its src attribute.

    		function applyDataUri(dataUri) {
    			$('#imageContainer').empty();
    			var img = $('', { src: dataUri}).appendTo($("#imageContainer"));
    			$("#imageContainer").css("display", "inline-block");
    		}

    At SVG export, ImageExporter generates a serialized SVG tag that includes a scalable vector graphics. To display it, insert the result as raw data into an empty DOM element.

    		function applySvg(svg) {
    			$("#imageContainer").html(svg);
    			$("#imageContainer").css("display", "inline-block");
    		}
    Back to index