0
votes

I'm using KineticJS to display images of a device similar to a webcam. To read the images I'm able to use a URL which return the JPG image. For testing purposes I have just added a event when the mouse cursor moves over the canvas. but updating the image fails. Only displaying the first one.

I think its a cache problem, but I'm not able to locate the problem.

Any help? Thanks in advance.

This is my JavaScript:

var stage;
var layer;
var dynamicImg;

stage = new Kinetic.Stage({
    container: "container",
    width: 640,
    height: 480,
    id: "myCanvas",
    name: "myCanvas"
});

layer = new Kinetic.Layer();
//gets the canvas context
var canvas = stage.getContainer();

function drawImage(imageObj) {
    dynamicImg = new Kinetic.Image({
        image: imageObj,
        x: 0,
        y: 0,
        width: 640,
        height: 480,
        draggable: false,
    });

    layer.add(dynamicImg);
    stage.add(layer);
    layer.draw();
};

var imageObj = new Image();
imageObj.onload = function () {
    drawImage(this);
};

imageObj.src = 'http://<ip>/live.cgi';

stage.on('contentMousemove', function () {
    imageObj = new Image();
    imageObj.onload = function () {
        layer.removeChildren();
        drawImage(imageObj);
        layer.draw();
    };
    imageObj.src = 'http://<ip>/live.cgi';
});
1

1 Answers

0
votes

Here's an alternate method that works faster and more efficiently:

  1. Create an html canvas element in memory and draw your incoming images on that canvas.

    var canvas=document.createElement('canvas');
    var ctx=canvas.getContext('2d');
    
  2. Create a Kinetic.Image using the canvas element as it's image source:

    dynamicImg = new Kinetic.Image({
        image: canvas,
        x: 0,
        y: 0,
        width: 640,
        height: 480,
        draggable: false,
    });
    
  3. Then you can just draw your new incoming images on the html canvas and your Kinetic.Image will automatically be updated with the new image.

    ctx.drawImage(yourNewImageObject,0,0);
    layer.drawScene();
    

This method is much faster and more efficient than recreating a new Kinetic.Image with each new image.

BTW...

I see your image source is 'http:///live.cgi'. If that means you're receiving a series of individual images, then you may have trouble. Individual images will take time to convert into individual Image Objects. If you are quickly receiving a large quantity of images then the delay in loading each Image Object will probably crash your app.

Instead, you might encode your incoming images into a video stream and pull the stream into an html video element. The html canvas can take a video element as a content source. Then you won't have the problems caused when loading individual Image Objects. Here's a link showing how to display a video element inside a canvas element: http://html5doctor.com/video-canvas-magic/.