我在Kineticjs中有一组进入图层,其中4个圆圈作为锚点来调整图像大小。单击按钮时,创建图像,组和锚点。 问题是当图像和圆圈创建圆圈时,图像不会显示,直到点击四个圆圈之间的区域为止。
var userGroup = new Kinetic.Group({
x: 0,
y: 0,
width: width,
height: height,
draggable: true
});
var layer = new Kinetic.Layer();
var imageObj = new Image();
var userImg = new Kinetic.Image({
id : 'userimg',
x: 0,
y: 0,
image: imageObj,
width: width,
height: height,
name: 'image'
});
userGroup.add(userImg);
layer.add(userGroup);
stage.add(layer);
addAnchor(userGroup, 0, 0, 'topLeft');
addAnchor(userGroup, width, 0, 'topRight');
addAnchor(userGroup, width, height, 'bottomRight');
addAnchor(userGroup, 0, height, 'bottomLeft');
layer.draw();
userGroup.on('dragstart', function() {
layer.moveToTop();
layer.draw();
});
layer.draw();
imageObj.src = uploadimg; // uploadimg = image url in my root web folder /images
layer.draw();
stage.draw();
});
答案 0 :(得分:1)
您的图片尚未加载,会发生什么。您将它分配给Kinetic.image并在图像加载之前更新图层。因此,您需要向图像的onload函数添加回调。
你应该这样做:
imageObj = new Image();
imageObj.onload = function() {
var userImg = new Kinetic.Image({
id : 'userimg',
x: 0,
y: 0,
image: imageObj,
width: width,
height: height,
name: 'image'
});
userGroup.add(userImg);
layer.draw();
};
imageObj.src = uploadimg;
一个好的做法是在你甚至在画布上绘制东西之前加载画布所需的所有图像。此代码段来自html5canvastutorials:
function loadImages(sources, callback) {
var images = {};
var loadedImages = 0;
var numImages = 0;
for(var src in sources) {
numImages++;
}
for(var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if(++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
用法:
var sources = {
darthVader: 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg',
yoda: 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg'
};
loadImages(sources, function(images) {
//all images are loaded in this callback function
});