我有带有3个JSON条目的JS对象,因为JavaScript循环使用KineticJS在画布上创建形状。我试图这样做,以便当我传递像素阈值时,在这种情况下为400px,它会创建一个警告框,其中JSON jstext与形状相关联。这是代码
var tools = [{'title':'method', 'jstext':'function newMethod() {'},
{'title':'var', 'jstext':'var'},
{'title':'end', 'jstext':'}'},
]
var startX = 20;
var startY = 30;
for (var i=0; i<tools.length; i++) {
alert(tools[i].jstext)
var x = new Kinetic.Rect({
x: startX,
y: startY,
width: 100,
height: 50,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 3,
draggable: true,
offset:10,
});
startY = startY + 65;
layer.add(x);
x.on('dragend', function() {
if (x.getAttr('x')>=400) {
console.log(tools[i].jstext)
};
}
它会创建矩形,它只会在最后一个形状被移动时记录,我希望它在移动任何形状时拉动该文本。有任何想法吗?谢谢!
答案 0 :(得分:1)
你可以:
代码将是这样的:
<!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-v4.7.2.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);
var startX = 20;
var startY = 30;
// create 5 test rects
for (var i=0; i<5; i++) {
newRect(startX,startY,i);
startY = startY + 65;
}
// function to create a new rect
function newRect(x,y,id){
var rect = new Kinetic.Rect({
id:id,
x: startX,
y: startY,
width: 100,
height: 50,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 3,
draggable: true,
offset:10,
});
// have the rect save its original XY
rect.originalX=x;
rect.originalY=y;
// on dragend, calc if the rect has moved >400px
rect.on("dragend",function(){
var dx=this.getX()-this.originalX;
var dy=this.getY()-this.originalY;
var id=this.getId();
if(dx*dx+dy*dy>400*400){
alert(id+" is currently beyond 400px of original XY");
}else{
console.log(id+" is currently inside 400px of original XY");
}
});
layer.add(rect);
layer.draw();
}
}); // end $(function(){});
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>