我试图获取鼠标指针坐标并将它们存储到一个数组(尾部)中,使得该数组仅限于100个对象。如果有额外的物品出现,旧的物体将被替换为新物体。基本上就像一个队列。 基本上我正在尝试使用较小半径的圆圈在基本圆圈之后创建一条轨迹。
这是我的js:
$(document).ready(function() {
var tail = {
x:0,
y:0
};
var i = 0;
var stage = new Kinetic.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
listening: true
});
var layer = new Kinetic.Layer({
listening: true
});
var layer = new Kinetic.Layer();
var player = new Kinetic.Circle({
x: 20,
y: 20,
radius: 6,
fill: 'cyan',
stroke: 'black',
draggable: true
});
var pixel = new Kinetic.Circle({
x: 20,
y: 20,
radius: 2,
width: stage.getWidth(),
height: stage.getHeight(),
fill: "white"
});
layer.add(player);
stage.add(layer);
// move the circle with the mouse
stage.getContent().addEventListener('mousemove', function() {
player.setPosition(stage.getPointerPosition());
console.log(stage.getPointerPosition());
var obj = {
x: stage.getPointerPosition().x,
y: stage.getPointerPosition().y
}
tail[i].push(obj);
++i;
console.log(tail[i]);
// pixel.setPosition(tail[i], tail[i + 1]);
layer.draw();
});
});
这是html:
<!DOCTYPE html>
<html>
<head>
<title>Collision Detection</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="../css/style.css"/>
</head>
<body>
<div id="container" style=" background:#000; margin:auto; float:left;"></div>
<script src="../js/jquery.min.js"></script>
<script src="../js/kinetic-v5.0.0.min.js"></script>
<script src="../js/main_kinetic.js"></script>
</body>
</html>
输出: 未捕获的TypeError:无法调用undefined main_kinetic.js的方法'push':46 对象{x:656,y:175} - &gt;控制台输出,返回光标位置。
答案 0 :(得分:1)
您可以为数据点创建自己的容器,只处理100(或者您想要的数量)。像这样:
var LimitedArray = function (upperLimit) {
var storage = [];
// default limit on length if none/invalid supplied;
upperLimit = +upperLimit > 0 ? upperLimit : 100;
this.push = function (item) {
storage.push(item);
if (storage.length > upperLimit) {
storage.shift();
}
return storage.length;
};
this.get = function (i) {
return storage[i];
};
this.iterateItems = function (iterator) {
var i, l = storage.length;
if (typeof iterator !== 'function') { return; }
for (i = 0; i < l; i++) {
iterator(storage[i]);
}
};
};
(见这里:http://jsfiddle.net/Frm27/4/)
然后您可以轻松跟踪数据点:
var trail = new LimitedArray(100);
// code...
// move the circle with the mouse
stage.getContent().addEventListener('mousemove', function() {
player.setPosition(stage.getPointerPosition());
console.log(stage.getPointerPosition());
var obj = {
x: stage.getPointerPosition().x,
y: stage.getPointerPosition().y
}
trail.push(obj);
trail.iterateItems(function (item) {
// Do something with each item.x and item.y
});
// pixel.setPosition(tail[i], tail[i + 1]);
layer.draw();
});
答案 1 :(得分:0)
除非你把它重新分配到某个地方,否则我看不到尾巴不是一个数组。
var tail = {
x:null,
y:0
};
如果您想要存储带有x和y坐标的对象,则需要
var tail = [{
x:null,
y:0
}];
tail.push(...);