I'm using the embedded Rhino Interpreter in Blue (a music composition environment for Csound) to generate a "score" (music notation). In blue you can do this by writing a function an then doing
score = myFunction()
My function gets an image using onLoad and extracts the pixel information, which will be used to generate the score. The problem is my function doesn't get enough time to load the image and return the data before it assigns it to a variable. I've tried using setTimeout() but that didn't help.
I tried this in a browser and it returns "undefined" indeed.
Basically I need a way of delaying the assignment to the score variable. Is this possible?
Thank you
function score(){
var img = new Image();
img.src = "http://static.webshopapp.com/shops/023001/files/024718445/256x256x2/major-dog-barbell-mini.jpg";
img.crossOrigin = "Anonymous";
var score = "abc";
img.onload = function(){
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var imgData=ctx.getImageData(0,0,canvas.width,canvas.height);
score = "i1 0 2 440 0.5\n"
for (var i=0;i<imgData.data.length;i+=4){
score += "i1 + 0.1 " + (imgData.data[i] + 500).toString() + " 0.5\n"
}
return score;
}
}
score = score();
// TRY THIS IN BROWSER - RETURNS UNDEFINED
//console.log(score())
What you need, is a callback function passed into the score function that will be fired when the image has been loaded: