MATLAB Community

MATLAB, community & more

Interactive web pages in MATLAB, part 3

As promised in my last post, this week we will complete our GUI by placing a dynamically-generated MATLAB figure back into the web page.

To show this, we will build upon the last example from last week. In that example, the page generates a sine wave with its settings derived from the HTML form. Instead of displaying the plot in a separate figure window, we’ll create it and print it to a file, where it will then be loaded back into the web page.

This demo (right-click to save) will only work in MATLAB web browser on Windows (sorry, Ken).

Clicking on the “Plot the Sine Wave” button causes the following to happen:

  1. The sine and plot are set-up using the form’s options, as before.
  2. The plot is exported to a PNG-file on disk, using the print command.
  3. The latest version of the image on disk is shown in the page, by refreshing an HTML element.

In order for these actions to work smoothly, the code makes use of a few tricks:

  • In the JavaScript function that creates the plot, we added some figure manipulations to the issued MATLAB command. The following code:

    commandURI+="f=figure;set(f,'Visible','off','units','pixels'," +
    "'Position',[0 0 270 210],'PaperPositionMode','auto');";

    1. Creates a new figure and saves its handle.
    2. Sets the figure’s properties so that figure is invisible (and therefore not shown to the user).
  • This code is followed with the print command to export the figure to disk. The specified options set the file-type to PNG and the print resolution to be that of the screen.
    commandURI+="print('sinewave.png','-dpng',sprintf('-f%d',f),'-r0');";
  • In the page, I’ve placed an HTML iframe to display the image. The iframe element allows me to refresh its content without having to reload the entire page, providing a smooth transition when the button is pressed.
    <iframe name="image" id="image" frameborder=0 marginwidth=0 marginheight=0 scrolling=no width=270 height=210 src="">

    The important properties of this iframe are: the id, which lets us get to it later, and the empty src, which gives us a blank page on startup.
  • The final piece to this code is the last line of JavaScript in the drawSine() function. The purpose of the code below is to give MATLAB enough time to process the plot command and make sure the file is saved to disk before it is reloaded. Here we set a timer for 0.5 seconds, and at the timeout replace the image-file source in the iframe.
    setTimeout("document.getElementById('image').src='sinewave.png';",500);

That’s pretty much it. I hope you’ve enjoyed this 3-part series, and good luck creating HTML GUIs in MATLAB. Let us know what kinds of interesting and crazy web pages you can think of.

|
  • print

评论

要发表评论,请点击 此处 登录到您的 MathWorks 帐户或创建一个新帐户。