当前位置: 动力学知识库 > 问答 > 编程问答 >

Kineticjs - Help uploading images to stage from input file

问题描述:

I am trying to allow users upload their own images to the kineticJS stage through an input in the html. I prefer to keep all my code in a separate js file, here is what i have so far:

$(document).ready(function() {

var stage = new Kinetic.Stage({

container: 'container',

width: 900,

height: 500

});

var layer = new Kinetic.Layer();

});

function addImage(){

var imageObj = new Image();

imageObj.onload = function() {

var myImage = new Kinetic.Image({

x: 140,

y: stage.getHeight() / 2 - 59,

image: imageObj,

width: 106,

height: 118

});

layer.add(myImage);

stage.add(layer);

}

var f = document.getElementById('uploadimage').files[0];

var name = f.name;

var url = window.URL;

var src = url.createObjectURL(f);

imageObj.src = src;

}

How do I expose the stage to the addImage() method? It is out of its scope at the moment and I havent been able to figure out how to solve the problem as the canvas doesn't show in the html until something is added to it. I need these images to be added as layers for future manipulation so want to use kineticJS. Any suggestions would be much appreciated!

网友答案:

http://jsfiddle.net/8XKBM/12/

I managed to get your addImage function working by attaching an event to it. If you use the Firebug console in Firefox or just press Ctrl+Shift+J you can get javascript errors. It turns out your function was being read as undefined, so now the alert is working, but your image isn't added because they aren't stored anywhere yet, like on a server (must be uploaded somewhere first)

I used jQuery to attach the event as you should use that instead of onclick='function()'

$('#addImg').on('click', function() {
    addImage();
  });

and changed

<div>
    <input type="file" name="img" size="5" id="uploadimage" />
    <button id='addImg' value="Upload" >Upload</button>
</div>
网友答案:

What you would really want to do is have the user upload the photos (to the server) on the fly using AJAX, (available with jQuery, doesn't interfere with KineticJS). Then, on success, you can draw the photo onto the canvas using your function. Make sure to use:

layer.draw() 

or

stage.draw() 

at the end of the addImage() function so that the photo is drawn on your canvas, as the browser does not draw the image until after the page loads and img.src is defined at the end. So, this will basically just require things to be in correct order rather than being difficult.

So, step 1: upload using AJAX (to server), step 2: add to stage, step 3: redraw stage

分享给朋友:
您可能感兴趣的文章:
随机阅读: