Robert Tupelo-Schneck Robert Tupelo-Schneck - 4 months ago 31
Javascript Question

How can Khan Academy computer programs be run offline or on my own website?

I have developed programs in Khan Academy's Computer Programming lessons that I would like to run outside of Khan Academy. How can that be done?

Answer

Khan Academy uses Processing.js, a JavaScript library for interacting with <canvas> elements. Although Processing is actually a language in its own right, Khan Academy uses JavaScript-only Processing.js code.

So you need to set up a web page that imports Processing.js, sets up a <canvas>, and builds a Processing.js instance on the canvas. Finally you need to make sure your Khan Academy code has all the members of the Processing.js instance in scope (I do this with with), plus some equivalent of Khan Academy's small modifications to Processing.js, like mouseIsPressed and getImage.

Here is some boilerplate that has been working for me. Probably further development will be required to get it working for more complicated examples; please post comments when you find examples that don't work.

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript</title>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.8/processing.min.js"></script>
</head>
<body>
  <canvas id="canvas"></canvas>
  <script>
    var canvas = document.getElementById("canvas");
    var processing = new Processing(canvas, function(processing) {
        processing.size(400, 400);
        processing.background(0xFFF);

        var mouseIsPressed = false;
        processing.mousePressed = function () { mouseIsPressed = true; };
        processing.mouseReleased = function () { mouseIsPressed = false; };

        var keyIsPressed = false;
        processing.keyPressed = function () { keyIsPressed = true; };
        processing.keyReleased = function () { keyIsPressed = false; };

        function getImage(s) {
            var url = "https://www.kasandbox.org/programming-images/" + s + ".png";
            processing.externals.sketch.imageCache.add(url);
            return processing.loadImage(url);
        }

        // use degrees rather than radians in rotate function
        var rotateFn = processing.rotate;
        processing.rotate = function (angle) {
            rotateFn(processing.radians(angle));
        };

        with (processing) {


            // INSERT YOUR KHAN ACADEMY PROGRAM HERE


        }
        if (typeof draw !== 'undefined') processing.draw = draw;
    });
  </script>
</body>
</html>
Comments