How to make KineticJs custom shape-Collection of common programming errors


  • Arif

    I am trying to make KineticJs html 5 custom shape.

    But it is not working in Google chrome. Not draggable in Firefox and also shape are not same in size.

    Can anybody tell why?

    live code http://jsfiddle.net/prantor19/wGE2a/8/

    var stage = new Kinetic.Stage({
        container: 'canvas-container',
        width: 500,
        height: 500,
    });
    
    var layer = new Kinetic.Layer();
    
    drawWindow = function(canvas) {
        var context = canvas.getContext();
        context.beginPath();
        context.moveTo(this.attrs.x,this.attrs.y);
        context.lineTo(this.attrs.width,this.attrs.y);
        context.lineTo(this.attrs.width,this.attrs.height);
        context.lineTo(this.attrs.x,this.attrs.height);
        context.closePath();
        context.clip();
        context.drawImage(img,this.attrs.img_x,this.attrs.img_y);
    }
    
    img = document.createElement('img');
    img.src= "http://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Nature_reserve_Kladrubska_hora_in_summer_2011_(17).JPG/1024px-Nature_reserve_Kladrubska_hora_in_summer_2011_(17).JPG";
    
    var window1 = new Kinetic.Shape({
        drawFunc: drawWindow,
        x: 0,
        y: 0,
        width: 100,
        height: 100,
        img:img,
        img_x:0,
        img_y:0,
        draggable: true
    });
    
    var window2 = new Kinetic.Shape({
        drawFunc: drawWindow,
        x: 10,
        y: 60,
        width: 100,
        height: 100,
        img:img,
        img_x:-250,
        img_y:0,
        draggable: true
    });
    
    pointercursor = function() {
        document.body.style.cursor = 'pointer';
    }
    defaultCursor = function() {
        document.body.style.cursor = 'default';
    }
    
    window1.on('mouseover',pointercursor );
    window1.on('mouseout', defaultCursor);
    window2.on('mouseover',pointercursor );
    window2.on('mouseout', defaultCursor);
    
    layer.add(window1);
    layer.add(window2);
    
    stage.add(layer);
    

  • sincebasic

    Your script has errors in it

    Unable to get image data from canvas because the canvas has been tainted by cross-origin data. kinetic-v4.3.2-beta.js:4365 Uncaught Error: SecurityError: DOM Exception 18

    Chrome refuse to work with cross domain images on cavas.

    For dragging, you need to add this set stroke for the shape

    stroke: 'black',
    

    and at the end of drawFunc

    canvas.fillStroke(this);
    

    Here is the my working version from yours

    http://jsfiddle.net/W7SGT/


  • Eric Rowell