Javascript 在KineticJS中选择图像
我在Kineticjs阶段有多个图像。我必须在单击图像时获取图像的x、y、高度和宽度属性。加载图像时,绑定一个单击事件:Javascript 在KineticJS中选择图像,javascript,html,kineticjs,Javascript,Html,Kineticjs,我在Kineticjs阶段有多个图像。我必须在单击图像时获取图像的x、y、高度和宽度属性。加载图像时,绑定一个单击事件: imageObj.onload = function(){ var currentImg = new Kinetic.Image({ // define x,y,W and H }); currentImg.on("click", function(e) { //x position for example
imageObj.onload = function(){
var currentImg = new Kinetic.Image({
// define x,y,W and H
});
currentImg.on("click", function(e) {
//x position for example
console.log(currentImg.getPosition().x);
});
}
下面是一个示例,演示了如何创建一个动能图像报告,单击时它是XY 先预加载所有图像 将单击事件附加到每个新的Kinetic.Image 示例代码和演示:
它工作得很好。但我这里有个问题。当加载第一个图像时,如果我没有在stage中单击该图像,当加载下一个图像时,如果我单击第二个图像,它将获取第二个图像的位置,但当我单击第一个图像时,它将获取第二个图像的位置,这很可能导致您必须声明两个不同的对象,如:currentImg1和当前img2。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.1.min.js"></script>
<style>
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
// first fully load all images into imgs[]
// then call start() when all are loaded
var imageURLs=[]; // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-2.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-4.jpg");
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
for(var i=0;i<imgs.length;i++){
addImage(imgs[i],i*60,10,50,50);
}
}
function addImage(img,x,y,w,h){
var image=new Kinetic.Image({
x:x,
y:y,
width:w,
height:h,
image:img,
draggable:true
});
image.on("click",function(){
var pos=this.position();
alert(parseInt(pos.x)+","+parseInt(pos.y));
});
layer.add(image);
layer.draw();
}
}); // end $(function(){});
</script>
</head>
<body>
<h4>Drag to new position. Click to get XY.</h4>
<div id="container"></div>
</body>
</html>