dopatraman
dopatraman

Reputation: 13908

cannot get processing script to run

I'm doing a Processing.js tutorial found here:http://processingjs.org/articles/jsQuickStart.html

When I load my document into the browser I get two errors:

uncaught exception: called Processing constructor without passing canvas element reference or id.

And

Access to restricted URI denied

xhr.send(null)

In regard to the first error, I pass the canvas element id like so:

var canvas = document.getElementById('canvas1');

I also checked and made sure that the canvas element in the HTML had the canvas1 id.

I'm not sure what went wrong with the second error.

Please help me see what I'm doing wrong.

This is my code:

function sketchProc(processing) {
        processing.draw = function() {
            var centerX = processing.width / 2; 
            var centerY = processing.height / 2;
            var maxArmLength = Math.min(centerX, centerY);

            function drawArm(position, lengthScale, weight) {
                processing.strokeWeight(weight);
                processing.line(centerX, centerY, 
                    centerX + Math.sin(position * 2 * Math.PI) * lengthScale * maxArmLength,
                    centerY - Math.cos(position * 2 * Math.PI) * lengthScale * maxArmLength);
            }

            processing.background(224);

            var now = new Date();

            var hoursPosition = (now.getHours() % 12 + now.getMinutes() / 60) / 12;
            drawArm(hoursPosition, 0.5, 5);
        }
    }

    var canvas = document.getElementById('canvas1');

    var processingInstance = new Processing(canvas, sketchProc);

Upvotes: 1

Views: 553

Answers (1)

"Access to restricted URI denied" suggests you were loading it from file:///, which means you can't do XHR file loading in any modern browser. You'll have to either run it from a localhost server (be that using Apache or a simple Python or PHP one-liner), or you'll have to put your files online in order to run your sketch.

Also, remember to verify that your "canvas" variable actually has any content. Running a script in the <head> before DOMContentLoaded means any document.getElementById will fail: your code will trigger before <body> has been built up. Either run your script at the end of the body, or (better) stick all your code inside a function and call that function as

document.addEventListener("DOMContentLoaded",myfunction,false):

making sure to add an extra line as first line in your function:

function myfunction() {
  document.removeEventListener("DOMContentLoaded",myfunction,false);
  [...]

Or, if you use frameworks like prototype, dojo, jquery, whatever, you can use their construct for executing JS only after the page has been built up.

Upvotes: 1

Related Questions