t6s
t6s

Reputation: 81

Clicking on array of images to add them to Konva stage

I am learning Konvajs and HTML5 Canvas and facing some issues:

  1. Creating a menu populated by an array of images and assign each image a id value equal to its image name. Completed without issue.

  2. Clicking on any one or multiple menu images to draw each image onto Konva stage for further manipulation like rotating etc. Having issues with this:

var pics = ["pic1.png", "pic2.png"]; 
$.each(pics, function( index, value )
{
  id = value.slice(32, -4);
  $('#menu').append("<img src=' " + value + " ' " + id + " " + "/>"); 
});

Full code at: https://jsfiddle.net/tommy6s/a44hbsc2/

Upvotes: 1

Views: 2261

Answers (1)

lavrton
lavrton

Reputation: 20373

Just make you code simpler:

//// INIT CANVAS
var stage = new Konva.Stage({
    container : "container",
    width : 400,
    height : 300
});
var layer = new Konva.Layer();
stage.add(layer);


/////MENU
var pics = ["http://konvajs.github.io/assets/lion.png", "http://konvajs.github.io/assets/monkey.png"];

var $menu = $('#menu');
$.each(pics, function( index, value ) {
    $("<img/>")    // create image
        .attr('src', value) // set src to image link
        .appendTo($menu)
        .on('click', function() {
            // this here is image object
            var src = this.src;
            // create new Konva.Image from src attribute
            Konva.Image.fromURL(src, function(image) {
                // make it draggable
                image.setAttrs({
                    draggable: true
                });
                // append to layer
                layer.add(image);
                // update layer
                layer.draw();
            })
        });
});

Demo: https://jsfiddle.net/6tnb2q2q/ (click on image to add it into stage)

Upvotes: 4

Related Questions