Not getting data in kinetic js throught JSON - javascript

i am stuck in passing data from php to kineticjs throught json below is the code
$arrParams = array('images' =>$images, 'captions' => $content);
init({"container":"slider","data":<?php echo json_encode($arrParams); ?>});
i want to pass the above Json array in my below given coded kineticjs code
var data;
var canvasWidth;
var canvasHeight;
var stage;
var layer = new Kinetic.Layer();
var imageNodes = [];
var imageObjects = [];
var imageBox = [];
var captionBox = [];
var textNodes = [];
var totalObjects = 0;
var objectLoaded = 0;
var currentSlide = false;
var defaultPosition = [];
var rightCardPosition = [];
var leftCardPosition = [];
function init(config) {
canvasWidth = config.width | 600;
canvasHeight = config.height | 300;
defaultPosition["x"] = canvasWidth / 4;
defaultPosition["y"] = canvasHeight + 5;
leftCardPosition["start"] = [];
leftCardPosition["end"] = [];
leftCardPosition["start"]["x"] = (canvasWidth / 3) - 180;
leftCardPosition["start"]["y"] = canvasHeight - 260;
leftCardPosition["end"]["x"] = (canvasWidth + 100);
leftCardPosition["end"]["y"] = -250;
rightCardPosition["start"] = [];
rightCardPosition["end"] = [];
rightCardPosition["start"]["x"] = (canvasWidth / 3) + 160;
rightCardPosition["start"]["y"] = canvasHeight - 300;
rightCardPosition["end"]["x"] = (canvasWidth + 100);
rightCardPosition["end"]["y"] = -250;
stage = new Kinetic.Stage({
container: config.container,
width: canvasWidth,
height: canvasHeight
});
totalObjects = data.images.length;
for (var i = 0; i < data.images.length; i++) {
totalObjects += data.captions[i].length;
}
for (var i = 0; i < data.images.length; i++) {
loadImage(data.images[i]);
loadCaption(data.captions[i]);
}
}
I am getting error like in the line
totalObjects = data.images.length;
data is undefine... which means images is not pass from the json array

You're encoding the JSON with PHP, now you just need to parse it with JavaScript and store it in your data variable.
data = JSON.parse(config.data);
Put this at the start of your init function and it should work for you.

Related

Javascript Canvas DrawImage dissapears previus state

my problem is when i use function drawImage() previus image on canvas has disappered. How i can rember previus state on my canvas?
I use react.
I try use save() and restore() but that not help me.
My code is:
updateCanvas(size, map, src) {
var PSI = 256;
var BSI = 16;
var IZ = PSI;
var crop_canvas = document.getElementById('myCanvas').getContext('2d');//this.refs.canvas.getContext('2d');
console.log(crop_canvas);
if(this.state.widthCanvas < size[0]) {
this.setState({
widthCanvas: size[0]
});
}
var oiw = size[0];
var iw = (oiw + PSI - 1) & ~(PSI - 1);
var dmap = map;
var pos_x = 0;
var pos_y = this.state.heightCanvas;
var myImage = [];
var loadnumber = this.state.loadNumber;
myImage[loadnumber] = new Image();
this.setState({
heightCanvas: this.state.heightCanvas+size[1]
});
myImage[loadnumber].src = src;
myImage[loadnumber].onload = function(e){
$.each(dmap, function(index, value){
var cord = [];
var y = (value / (iw / PSI)) | 0;
var x = (value % (iw / PSI)) | 0;
cord[0] = (x * PSI);
cord[1] = (y * PSI);
var cut_x = ((cord[0] * (2 * BSI + PSI) / PSI + BSI) * IZ / (PSI)) | 0;
var cut_y = ((cord[1] * (2 * BSI + PSI) / PSI + BSI) * IZ / (PSI)) | 0;
crop_canvas.drawImage(myImage[loadnumber] , cut_x, cut_y, PSI, PSI, pos_x, pos_y, PSI, PSI);
pos_x=pos_x+PSI;
if(pos_x > oiw){
pos_y=pos_y+PSI;
pos_x = 0;
}
});
var that = this;
setTimeout(function(){
that.LoaderImage(parseInt(that.state.loadNumber)+1);
},1000);
}.bind(this);
}

How to set onclick event in moving object in canvas?

How to set on click event in moving object in canvas? Also how to move the object bottom to top in canvas.I am newly in javascript i am going to develop the sample like when the page open, objects like square and circle randomly come from bottom of the page and move to top automatically.
You need to establish an array that will have your moving objects in it. When the onclick handler fires, check to see if the coordinates of the click are inside any of the objects in the array.
On each animation frame, move your objects up by subtracting some of the y coordinate from each object.
//width and height of canvas...
var rW = 400;
var rH = 500;
var coinImage = getCoinImage();
var coinsOnScreen = [];
var risingSpeed = 100; //pixels per second...
var coinSize = 75;
var lastAnimationTime = 0;
var howLongUntilNextCoin = 1000;
var nextCoinOnScreen = 0;
function doDraw() {
var can = document.getElementById("myCanvas");
can.width = rW;
can.height = rH;
var context = can.getContext("2d");
//Erase the canvas
context.fillStyle = "#FFFFFF";
context.fillRect(0, 0, rW, rH);
if (new Date().getTime() - nextCoinOnScreen > 0) {
var newX = Math.floor(Math.random() * rW) + 1;
var newY = rH + 50;
var newCoin = {
x: newX,
y: newY
};
coinsOnScreen.push(newCoin);
nextCoinOnScreen = new Date().getTime() + howLongUntilNextCoin;
}
//Now draw the coins
if (lastAnimationTime != 0) {
var deltaTime = new Date().getTime() - lastAnimationTime;
var coinRisePixels = Math.floor((deltaTime * risingSpeed) / 1000);
var survivingCoins = [];
for (var i = 0; i < coinsOnScreen.length; i++) {
var coin = coinsOnScreen[i];
coin.y = coin.y - coinRisePixels;
//the stl variable controlls the alpha of the image
if (coin.y + 50 > 0) {
context.drawImage(coinImage, coin.x, coin.y);
//this coin is still on the screen, so promote it to the new array...
survivingCoins.push(coin);
}
}
coinsOnScreen = survivingCoins;
}
lastAnimationTime = new Date().getTime();
//Wait, and then call this function again to animate:
setTimeout(function() {
doDraw();
}, 30);
}
function setupClickHandler() {
var can = document.getElementById("myCanvas");
//Here is the onclick handler
can.onclick = function(e) {
var x = e.clientX;
var y = e.clientY;
var survivingCoins = [];
for (var i = 0; i < coinsOnScreen.length; i++) {
var coin = coinsOnScreen[i];
//check to see if this coin has been clicked...
if (x > coin.x && x < coin.x + coinSize && y > coin.y && y < coin.y + coinSize) {
//ths coin will disappear because it is not inserted into the new array...
console.log("Coin was clicked!! " + x + " " + y);
} else {
survivingCoins.push(coin);
}
}
coinsOnScreen = survivingCoins;
};
}
doDraw();
setupClickHandler();
function getCoinImage() {
var image = new Image(50, 50);
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAACXBIWXMAAAsTAAALEwEAmpwYAAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAAOWUlEQVR42mL8sYUBJ2BkhGAGKGZkQKUZYPz/QPo/gzwDE4MJEBswMDO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mv2ABt2EWQYyGNQBAlnExoGW1nGMDLIilUz/8SRDcD5ih5gNSkqgEU8UT/xnCIA2p7ACgABiIpA8bgMN8AUaeByWZ0CW/PwKYYPnx9mh/Rg0D8AwrLSBiSNPBsH6QKAxXVC3ABQbILP/Io3mA9VcBmI/8PQBHgAQQITHLyCecQfiNiD+CRu6BA0Y/ITOr4Im+0EOAdHgRQJoLV3k0okRWpzC9XBB8xPQrF9fEcUxUP1/IJ4K5LgA5c8RciZAADE+mog/4/1HarIA+XZAfheQZY5R1kPrBlBxyciE1ORGtgxpFcT/v4hZKwak1gO0v3QeSNcAOdsYocHNyIi/gAEIIFJXBx2CNmMSgbZlAS3Ugvf+YcM/jEhLP5jgqyfgIx7Ia0sYkZZKQX18D0jNBPJnQHs7RAOAACI1RhDjXsDaH0j5A1lRQLY9tHlIDvgJdPgxIL0CiNcCPfcWY20YETECEECUeASRbP4zaILaPUC+EZCtDmQD27oMvDhMBeWsh0BH3QTSF4BuOwBkX4LFCSO2RW5EeAQgwACQYpcXuHTdswAAAABJRU5ErkJggg==";
return image;
}
<canvas id="myCanvas"></canvas>

pdf.js open or generate pdf from Uint8Array

I have the below base64 encoded string which contains the pdf file.
I want to convert the base64 string to a Uint8Array as Uint8Array is supported from IE9 forward, and than I want to open pdf using pdf.js
I am using following code,
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
var pdfAsDataUri = "data:application/pdf;base64," + base64encodedString;
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
base64encodedString = JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9MZW5ndGggMTE1My9GaWx0ZXIvRmxhdGVEZWN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RhbG9nL1BhZ2VzIDQgMCBSPj4KZW5kb2JqCjcgMCBvYmoKPDwvQ3JlYXRvcihDbGVhcnRyYWNrKS9Qcm9kdWNlcihpVGV4dK4gNS4yLjEgqTIwMDAtMjAxMiAxVDNYVCBCVkJBKS9UaXRsZShBY2FkZW15IE9yZGVyIEluc3BlY3Rpb24gUERGKS9Nb2REYXRlKEQ6MjAxNTEyMDMwOTI5NTItMDUnMDAnKS9BdXRob3IoQ2xlYXJ0cmFjaykvQ3JlYXRpb25EYXRlKEQ6MjAxNTEyMDMwOTI5NTItMDUnMDAnKT4+CmVuZG9iagp4cmVmCjAgOAowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDE0MDIgMDAwMDAgbiAKMDAwMDAwMTQ5MSAwMDAwMCBuIAowMDAwMDAwMDE1IDAwMDAwIG4gCjAwMDAwMDE1NzkgMDAwMDAgbiAKMDAwMDAwMTIzNiAwMDAwMCBuIAowMDAwMDAxNjQyIDAwMDAwIG4gCjAwMDAwMDE2ODcgMDAwMDAgbiAKdHJhaWxlcgo8PC9Sb290IDYgMCBSL0lEIFs8Y2RmYjYwYjE2YjY0YTM5MGZiNGQ1ZTI1ZGU4ZmNkMTg+PGQ2OWY0NzdkZTUxZGQ0YjVhMzZkZGEwZjJmMDMzZGJiPl0vSW5mbyA3IDAgUi9TaXplIDg+PgpzdGFydHhyZWYKMTg5OAolJUVPRgo=
But pdf is not getting generated or open in browser, any kind of suggestions or help will be appreciated.
I use this in my projects and it works fine.
HTML
<div id="myCanvasContainer"></div>
JS
function renderPDF( pdfBase64 ) {
var pdfUint8Array = base64ToUint8Array( pdfBase64 );
var canvasContainer = document.getElementById('myCanvasContainer');
var options = options || { scale: 1.5 };
function renderPage(page) {
var viewport = page.getViewport(options.scale);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
canvas.height = viewport.height;
canvas.width = viewport.width;
canvasContainer.appendChild(canvas);
page.render(renderContext);
}
function renderPages(pdfDoc) {
for(var num = 1; num <= pdfDoc.numPages; num++)
pdfDoc.getPage(num).then(renderPage);
}
function base64ToUint8Array(base64) {
var raw = atob(base64);
var uint8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
}
PDFJS.disableWorker = true;
PDFJS.getDocument(pdfUint8Array).then(renderPages);
}
Hope it helps.

When dynamically creating images, why is the image array empty?

What I am trying to do is load images dynamically and then draw them on the screen. However, when I call console.log(images), it is empty.
Here is the code:
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");
var images = new Array();
for (i = 0; i < mattes_array.length; i++)
{
var imgsrc = mattes_array[i]["imgsrc"];
var total_size = mattes_array[i]["total_size"];
var cpu = mattes_array[i]["cpu"];
var cid = mattes_array[i]["cid"];
var imageObj = new Image();
imageObj.onload = function() {
images[i] = imageObj;
console.log(images[i]);
};
imageObj.id = "matte_" + cid;
imageObj.src = imgsrc;
}
console.log(images); //this is empty
for (i = 0; i < mattes_array.length; i++)
{
var imgsrc = mattes_array[i]["imgsrc"];
var total_size = mattes_array[i]["total_size"];
var cpu = mattes_array[i]["cpu"];
var cid = mattes_array[i]["cid"];
var pattern = ctx.createPattern(images[i], 'repeat');
ctx.strokeStyle = pattern;
ctx.lineWidth = width - opening_width - (total_size * 2);
ctx.strokeRect(0, 0, width, height);
}
}
I have also tried doing it in one loop, but it seems to only draw the last image:
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");
var images = new Array();
for (i = 0; i < mattes_array.length; i++)
{
var imgsrc = mattes_array[i]["imgsrc"];
var total_size = mattes_array[i]["total_size"];
var cpu = mattes_array[i]["cpu"];
var cid = mattes_array[i]["cid"];
var imageObj = new Image();
imageObj.onload = function() {
var pattern = ctx.createPattern(imageObj, 'repeat');
ctx.strokeStyle = pattern;
ctx.lineWidth = width - opening_width - (total_size * 2);
ctx.strokeRect(0, 0, width, height);
};
imageObj.id = "matte_" + cid;
imageObj.src = imgsrc;
}
}
Here is an image of what I am trying to do:
Images load asynchronously. You're trying to draw them before they are loaded. Give this a try:
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");
var images = new Array();
var loaded = 0;
for (i = 0; i < mattes_array.length; i++)
{
var imgsrc = mattes_array[i]["imgsrc"];
var total_size = mattes_array[i]["total_size"];
var cpu = mattes_array[i]["cpu"];
var cid = mattes_array[i]["cid"];
var imageObj = new Image();
imageObj.onload = function() {
images[i] = imageObj;
console.log(images[i]);
if ( ++loaded === mattes_array.length ) onloaded();
};
imageObj.id = "matte_" + cid;
imageObj.src = imgsrc;
}
function onloaded() {
console.log(images); //this is won't be empty anymore
for (i = 0; i < mattes_array.length; i++)
{
var imgsrc = mattes_array[i]["imgsrc"];
var total_size = mattes_array[i]["total_size"];
var cpu = mattes_array[i]["cpu"];
var cid = mattes_array[i]["cid"];
var pattern = ctx.createPattern(images[i], 'repeat');
ctx.strokeStyle = pattern;
ctx.lineWidth = width - opening_width - (total_size * 2);
ctx.strokeRect(0, 0, width, height);
}
}
}

Scope issue with Coffeescript

I have some strange scope issue in Coffeescript.
I can't access to _this from the function #qr.callback, the _this doesn't seem to pass well. I never change this.imgName so the only reason that It doesn't work could be that _this is'nt passed well.
decode:(#callback) ->
_this= this
console.log 'before',_this.imgName
#qr= new QrCode()
#qr.callback= () ->
console.log "after:", _this.imgName
#qr.decode("data:image/png;base64,#{#base64Data}")
Edit:
I have tried using
console.log 'before',#imgName
#qr= new QrCode()
#qr.callback= () =>
console.log "after:", #imgName
#qr.decode("data:image/png;base64,#{#base64Data}")
But the output is the same
Edit2: QrCode code: This code comes from https://github.com/LazarSoft/jsqrcode. Howewer, as the source code of LazarSoft https://github.com/LazarSoft/jsqrcode/blob/master/src/qrcode.js did'nt contain a QrCode object that you could instantiate many times , I transformed the code to create many different instances of QrCode by creating a QrCode function instead of a global object qrcode.
QrCode= function ()
{
this.imagedata = null;
this.width = 0;
this.height = 0;
this.qrCodeSymbol = null;
this.debug = false;
this.sizeOfDataLengthInfo = [ [ 10, 9, 8, 8 ], [ 12, 11, 16, 10 ], [ 14, 13, 16, 12 ] ];
this.callback = null;
this.decode = function(src){
if(arguments.length==0)
{
var canvas_qr = document.getElementById("qr-canvas");
var context = canvas_qr.getContext('2d');
this.width = canvas_qr.width;
this.height = canvas_qr.height;
this.imagedata = context.getImageData(0, 0, this.width, this.height);
this.result = this.process(context);
if(this.callback!=null)
this.callback(this.result);
return this.result;
}
else
{
var image = new Image();
_this=this
image.onload=function(){
//var canvas_qr = document.getElementById("qr-canvas");
var canvas_qr = document.createElement('canvas');
var context = canvas_qr.getContext('2d');
var canvas_out = document.getElementById("out-canvas");
if(canvas_out!=null)
{
var outctx = canvas_out.getContext('2d');
outctx.clearRect(0, 0, 320, 240);
outctx.drawImage(image, 0, 0, 320, 240);
}
canvas_qr.width = image.width;
canvas_qr.height = image.height;
context.drawImage(image, 0, 0);
_this.width = image.width;
_this.height = image.height;
try{
_this.imagedata = context.getImageData(0, 0, image.width, image.height);
}catch(e){
_this.result = "Cross domain image reading not supported in your browser! Save it to your computer then drag and drop the file!";
if(_this.callback!=null)
_this.callback(_this.result);
return;
}
try
{
_this.result = _this.process(context);
}
catch(e)
{
// console.log('error:'+e);
_this.result = "error decoding QR Code";
}
if(_this.callback!=null)
_this.callback(_this.result);
}
image.src = src;
}
}
this.decode_utf8 = function ( s )
{
return decodeURIComponent( escape( s ) );
}
this.process = function(ctx){
var start = new Date().getTime();
var image = this.grayScaleToBitmap(this.grayscale());
//var image = this.binarize(128);
if(this.debug)
{
for (var y = 0; y < this.height; y++)
{
for (var x = 0; x < this.width; x++)
{
var point = (x * 4) + (y * this.width * 4);
this.imagedata.data[point] = image[x+y*this.width]?0:0;
this.imagedata.data[point+1] = image[x+y*this.width]?0:0;
this.imagedata.data[point+2] = image[x+y*this.width]?255:0;
}
}
ctx.putImageData(this.imagedata, 0, 0);
}
//var finderPatternInfo = new FinderPatternFinder().findFinderPattern(image);
var detector = new Detector(image,this);
var qRCodeMatrix = detector.detect();
/*for (var y = 0; y < qRCodeMatrix.bits.Height; y++)
{
for (var x = 0; x < qRCodeMatrix.bits.Width; x++)
{
var point = (x * 4*2) + (y*2 * this.width * 4);
this.imagedata.data[point] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0;
this.imagedata.data[point+1] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0;
this.imagedata.data[point+2] = qRCodeMatrix.bits.get_Renamed(x,y)?255:0;
}
}*/
if(this.debug)
ctx.putImageData(this.imagedata, 0, 0);
var reader = Decoder.decode(qRCodeMatrix.bits,this);
var data = reader.DataByte;
var str="";
for(var i=0;i<data.length;i++)
{
for(var j=0;j<data[i].length;j++)
str+=String.fromCharCode(data[i][j]);
}
var end = new Date().getTime();
var time = end - start;
console.log(time);
return this.decode_utf8(str);
//alert("Time:" + time + " Code: "+str);
}
this.getPixel = function(x,y){
if (this.width < x) {
throw "point error";
}
if (this.height < y) {
throw "point error";
}
point = (x * 4) + (y * this.width * 4);
p = (this.imagedata.data[point]*33 + this.imagedata.data[point + 1]*34 + this.imagedata.data[point + 2]*33)/100;
return p;
}
this.binarize = function(th){
var ret = new Array(this.width*this.height);
for (var y = 0; y < this.height; y++)
{
for (var x = 0; x < this.width; x++)
{
var gray = this.getPixel(x, y);
ret[x+y*this.width] = gray<=th?true:false;
}
}
return ret;
}
this.getMiddleBrightnessPerArea=function(image)
{
var numSqrtArea = 4;
//obtain middle brightness((min + max) / 2) per area
var areaWidth = Math.floor(this.width / numSqrtArea);
var areaHeight = Math.floor(this.height / numSqrtArea);
var minmax = new Array(numSqrtArea);
for (var i = 0; i < numSqrtArea; i++)
{
minmax[i] = new Array(numSqrtArea);
for (var i2 = 0; i2 < numSqrtArea; i2++)
{
minmax[i][i2] = new Array(0,0);
}
}
for (var ay = 0; ay < numSqrtArea; ay++)
{
for (var ax = 0; ax < numSqrtArea; ax++)
{
minmax[ax][ay][0] = 0xFF;
for (var dy = 0; dy < areaHeight; dy++)
{
for (var dx = 0; dx < areaWidth; dx++)
{
var target = image[areaWidth * ax + dx+(areaHeight * ay + dy)*this.width];
if (target < minmax[ax][ay][0])
minmax[ax][ay][0] = target;
if (target > minmax[ax][ay][1])
minmax[ax][ay][1] = target;
}
}
//minmax[ax][ay][0] = (minmax[ax][ay][0] + minmax[ax][ay][1]) / 2;
}
}
var middle = new Array(numSqrtArea);
for (var i3 = 0; i3 < numSqrtArea; i3++)
{
middle[i3] = new Array(numSqrtArea);
}
for (var ay = 0; ay < numSqrtArea; ay++)
{
for (var ax = 0; ax < numSqrtArea; ax++)
{
middle[ax][ay] = Math.floor((minmax[ax][ay][0] + minmax[ax][ay][1]) / 2);
//Console.out.print(middle[ax][ay] + ",");
}
//Console.out.println("");
}
//Console.out.println("");
return middle;
}
this.grayScaleToBitmap=function(grayScale)
{
var middle = this.getMiddleBrightnessPerArea(grayScale);
var sqrtNumArea = middle.length;
var areaWidth = Math.floor(this.width / sqrtNumArea);
var areaHeight = Math.floor(this.height / sqrtNumArea);
var bitmap = new Array(this.height*this.width);
for (var ay = 0; ay < sqrtNumArea; ay++)
{
for (var ax = 0; ax < sqrtNumArea; ax++)
{
for (var dy = 0; dy < areaHeight; dy++)
{
for (var dx = 0; dx < areaWidth; dx++)
{
bitmap[areaWidth * ax + dx+ (areaHeight * ay + dy)*this.width] = (grayScale[areaWidth * ax + dx+ (areaHeight * ay + dy)*this.width] < middle[ax][ay])?true:false;
}
}
}
}
return bitmap;
}
this.grayscale = function(){
var ret = new Array(this.width*this.height);
for (var y = 0; y < this.height; y++)
{
for (var x = 0; x < this.width; x++)
{
var gray = this.getPixel(x, y);
ret[x+y*this.width] = gray;
}
}
return ret;
}
}
var image = new Image();
_this=this
May lightning strike you, you're coding CoffeeScript too much! You forgot a var declaration here, so the ninth invocation of decode overwrites the global _this with its this instance - and when each decoding is finished, they all call the same callback.
Fix it by using
var _this = this;
or
var image = new Image,
_this = this;
or by using CoffeeScript everywhere :-)

Categories