Question

I have a canvas on which I can currently add text layers and images from flickr. What I'm trying to do is make it possible to upload an image to the canvas with the html input.

I am using this to upload images from flickr:

$(".search form.image-search").submit(function(){
        $(".search li").remove();
        $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags="+$(".search input[name=q]").val()+"&tagmode=any&format=json&jsoncallback=?",
            function(data) {
            $.each(data.items, function(i,item) {
                var img = $("<img/>").attr("src", item.media.m);
                img.attr("title", item.title);
                $("<li></li>").append(img).appendTo(".search ul");
                if ( i == 8 ) return false;
            });
        });
        return false;
    }); 

$(".search img").live("click", function() {
    jCollage.addLayer($(this).context).setTitle($(this).attr("title"));
    updateLayers(jCollage.getLayers());
    $("#layer_" + (jCollage.getLayers().length - 1)).addClass("selected");
});

I did have the image upload function working on an old canvas but now I have started working with another canvas which was better I couldn't get it to work anymore. My old way to upload image to a canvas was this:

var imageLoader = document.getElementById('uploader');
    imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');

function handleImage(e){
    var reader = new FileReader();
    reader.onload = function(event){
        var imgNew = new Image();
        imgNew.onload = function(){
s.addShape(new Shape(60,60,imgNew.width/2,imgNew.height/2,imgNew));
        }
        imgNew.src = event.target.result;
    }
    reader.readAsDataURL(e.target.files[0]);     
}

I have tried some things to implement this into my new canvas but since I'm not very experienced with Javascript I couldn't get this to work.

Here is a working (old) version of my canvas to make everything more clear and for you guys to test on:
http://codepen.io/anon/pen/daqnt/?editors=001

If someone could help me get this to work it would be great!

Was it helpful?

Solution

The same general approach should work. However, your new library expects an <img> DOM element when adding a layer.

The following does what you want:

http://codepen.io/nonplus/full/fjzcv/

  $("#uploader").change(function(e) {
      var reader = new FileReader();
      var title = e.target.value.replace(/.*[\\/]|(\.[^\.]+$)/g, "");
      reader.onload = function(event){
          var $img = $("<img/>").attr("src", event.target.result);
          jCollage.addLayer($img.get(0)).setTitle(title);
          updateLayers(jCollage.getLayers());
          $("#layer_" + (jCollage.getLayers().length - 1)).addClass("selected");    
      }
      reader.readAsDataURL(e.target.files[0]);
  });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top