Search code examples
javascripthtmlkineticjs

kinetics user upload an image


I have a kineticjs box with text input and an "onLoad" image (Yoda). I need to implement this "imageLoader" (Fiddle)

I have this from a canvas I put together but cant get it into my new kinetics Fiddle

function loadThisImage(src) {
    img = new Image();
    img.onload = function () {
        draw(img, true, false);
    };
    img.src = src;
    img.view = {
        left: 42,
        top: 20,
        width: 160,
        height: 120,
        z: 0
    };
}


var ctx = canvas.getContext('2d');


function draw(img, withAnchors, withBorders) {
    // clear the canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // draw the image
    var view = img.view;
    ctx.drawImage(img, 0, 0, img.width, img.height, view.left, view.top, view.width, view.height);

    // optionally draw the draggable anchors
    if (withAnchors) {
        drawDragAnchor(view.left, view.top);
        drawDragAnchor(view.left + view.width, view.top);
        drawDragAnchor(view.left + view.width, view.top + view.height);
        drawDragAnchor(view.left, view.top + view.height);
    }

Would appreciate if someone could help me put my "upload Image" to my kinetics. thanks in advance :)


Solution

  • Just adapting the code from that "imageLoader" fiddle to create a new Kinetic.Image and add it to the layer instead of drawing straight to a canvas context.

    //image loader
    var imageLoader = document.getElementById('imageLoader');
        imageLoader.addEventListener('change', handleImage, false);
    
    function handleImage(e){
        var reader = new FileReader();
        reader.onload = function(event){
            var img = new Image();
            img.onload = function(){
                layer.add(new Kinetic.Image({
                    x: 200,
                    y: 50,
                    image: img,
                    width: img.width,
                    height: img.height,
                    draggable: true
                }));
                text.moveToTop();
                layer.draw();
            }
            img.src = event.target.result;
        }
        reader.readAsDataURL(e.target.files[0]);     
    }
    

    Fiddle: http://jsfiddle.net/pDW34/14/