Christian Heilmann

Posts Tagged ‘helpers’

Helper functions: Resize images to a variable thumbnail size

Wednesday, February 1st, 2012

As part of the “Creating thumbnails with drag and drop and HTML5 canvas” post on MDN today, I spent some time creating a short and working resizing function that takes an arbitrary image and re-sizes it to fit into a thumbnail of a certain width and height. After a few failed attempts I googled around and actually found one of my old PHP/GD tutorials I thought I had deleted years ago. Well, the function still works :)

Without further ado, here is the resize() function (also available as a gist).

function resize( imagewidth, imageheight, thumbwidth, thumbheight ) {
    var w = 0, h = 0, x = 0, y = 0,
        widthratio  = imagewidth / thumbwidth,
        heightratio = imageheight / thumbheight,
        maxratio    = Math.max( widthratio, heightratio );
    if ( maxratio > 1 ) {
        w = imagewidth / maxratio;
        h = imageheight / maxratio;
    } else {
        w = imagewidth;
        h = imageheight;
    }
    x = ( thumbwidth - w ) / 2;
    y = ( thumbheight - h ) / 2;
    return { w:w, h:h, x:x, y:y };
  };

The returned data is the width and the height of the image and the x and y position in the thumbnail – ready to use in HTML5 canvas.

You can test the function in this Fiddle:

Generating tutorials from source comments with Tutorialbuilder

Tuesday, May 13th, 2008

I am spending far too much time keeping explanation tutorials of scripts in sync with changes in the code. This is why I wrote myself a PHP solution to do the work for me. I’ve found over the years that the best way to explain a script is to :

  • Show an example
  • Show the full source code
  • Show the source code bit by bit followed by explanations what each part does

If you go and check Tutorialbuilder you’ll see that I managed to automate most of this with a PHP script. It does the following for you:

  • It generates the tutorial parts from comments in the script source code.
  • It converts the source code to displayable code (encoding it, adding line numbers, allowing for lines to be highlighted)
  • It creates a downloadable version of the script with a correct file name
  • It creates an executable version of the script without comments to link to with a script element.
  • It can minify the script (remove all whitespace to cut down on file size)

In other words, it turns this source script into a tutorial like this using a template and some CSS (most taken from the YUI).

It is not a replacement for JSDoc but instead catered to be easier to use and explain the functionality of code rather than the syntax of the JS code itself.

Tutorialbuilder is licensed with BSD, so go nuts using it for yourself.