Reputation: 11
I was going through HTML5 Canvas Kinteticjs tutorial for adding image. I want to add multiple images and layer them.
The example below has two images but both are the same.
The question: How do i load 2 different images?
Upvotes: 1
Views: 4201
Reputation: 27738
As you may already know, Image is not a KineticJS object, but Kinetic.Image is.
So, as long as you make one-to-one connection between Image and Kinetic.Image, you are ok with it.
The example on the html5canvastutorials.com uses Image.onload function to create Kinetic.Image. This confuses so many people. However you don't need to do that if you preload images.
The purpose of creating Kinetic.Image when Image is loaded is not to have invalid(broken) images on canvas. So, if you make all you Images valid, by preloading those, you don't need to use image.onload, which make you confused, at all.
To preload iamges,
Upvotes: 1
Reputation: 16544
You will have to create two image objects instead of one, and on load of both, you can put both images onto the canvas.
var imgObj1 = new Image();
var imgObj2 = new Image();
var loadCount = 0;
imgObj1.onload = function() {
loadCount++;
if(loadCount==2) putOnCanvas();
};
imgObj2.onload = function() {
loadCount++;
if(loadCount==2) putOnCanvas();
};
imgObj1.src = ".....";
imgObj2.src = ".....";
function putOnCanvas() {
var yoda = new Kinetic.Image({
x: 140,
y: stage.getHeight() / 2 - 59,
image: imageObj1,
width: 106,
height: 118
});
var filteredYoda = new Kinetic.Image({
x: 320,
y: stage.getHeight() / 2 - 59,
image: imageObj2,
width: 106,
height: 118
});
// add the shape to the layer
layer.add(yoda);
layer.add(filteredYoda);
// add the layer to the stage
stage.add(layer);
// apply grayscale filter to second image
filteredYoda.applyFilter(Kinetic.Filters.Grayscale, null, function() {
layer.draw();
});
}
Upvotes: 1