我想将星星放在一棵树上并检测星星掉落在哪棵树上,这样我就可以突出显示并最终选择它。但我不仅仅是移动这颗恒星。
我之所以选择kineticjs是因为它适用于触摸屏,所以如果可能的话我不想使用别的东西。 (除非它同时适用于触摸屏和鼠标)
这是我的javascript:
<script defer="defer">
function drawImage(imageObj) {
var stage = new Kinetic.Stage({
container: "star",
width: 900,
height: 500
});
var layer = new Kinetic.Layer();
// star
var star = new Kinetic.Image({
image: imageObj,
x: 376,
y: 30,
width: 40,
height: 46,
draggable: true,
draw: false
});
// add cursor styling
star.on('mouseover', function() {
document.body.style.cursor = 'pointer';
});
star.on('mouseout', function() {
document.body.style.cursor = 'default';
});
layer.add(star);
stage.add(layer);
}
var imageObj = new Image();
imageObj.onload = function() {
drawImage(this);
};
imageObj.src = 'http://upload.wikimedia.org/wikipedia/commons/d/df/Star_icon_1.png';
</script>
请查看完整代码的小提琴: http://jsfiddle.net/hpq7rpnh/1/
答案 0 :(得分:1)
将树木添加为自己的对象,然后可以检查星星和树木之间的碰撞:
var starLayer = new Kinetic.Layer(); // its own layer, index should be above tree layer
var treeLayer = new Kinetic.Layer(); // its own layer
stage.add(treeLayer);
stage.add(starLayer);
var tree = new Kinetic.Rectangle( ... );
treeLayer.add(tree);
var tree2 = new Kinetic.Rectangle( ... ); // another tree at another coordinate
treeLayer.add(tree2); // assuming you have a layer for Trees ONLY already
稍后,当用户放弃星形时,您需要检查碰撞
// sample bounding box collision detection
function checkCollision(){
var trees = treeLayer.getChildren(); // gets all the trees
for(tree in trees)
if(star.xCoord > tree.xCoord && star.xCoord + star.width < tree.xCoord + tree.width ... same for y coordinates)
}