您的位置:首页 > Web前端 > JavaScript

HTML5:Canvas复杂的拖拽和KineticJS界限教程

2013-10-21 21:20 316 查看
限制的移动节点被拖掉KineticJS内部地区,我们可以使用dragBoundFunc属性定义的边界节点不能交叉。
产品说明:拖放浅蓝色矩形和观察,它必然低于一个假想边界在y = 50。拖放黄色矩形和观察,它必然在一个假想的圆。

<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
<body>
<div id="container"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script>
<script defer="defer">
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();

// bound below y=50
var blueGroup = new Kinetic.Group({
x: 100,
y: 70,
draggable: true,
dragBoundFunc: function(pos) {
var newY = pos.y < 50 ? 50 : pos.y;
return {
x: pos.x,
y: newY
};
}
});

// bound inside a circle
var yellowGroup = new Kinetic.Group({
x: stage.getWidth() / 2,
y: 70,
draggable: true,
dragBoundFunc: function(pos) {
var x = stage.getWidth() / 2;
var y = 70;
var radius = 50;
var scale = radius / Math.sqrt(Math.pow(pos.x - x, 2) + Math.pow(pos.y - y, 2));
if(scale < 1)
return {
y: Math.round((pos.y - y) * scale + y),
x: Math.round((pos.x - x) * scale + x)
};
else
return pos;
}
});

var blueText = new Kinetic.Text({
fontSize: 26,
fontFamily: 'Calibri',
text: 'bound below',
fill: 'black',
padding: 10
});

var blueRect = new Kinetic.Rect({
width: blueText.getWidth(),
height: blueText.getHeight(),
fill: '#aaf',
stroke: 'black',
strokeWidth: 4
});

var yellowText = new Kinetic.Text({
fontSize: 26,
fontFamily: 'Calibri',
text: 'bound in circle',
fill: 'black',
padding: 10
});

var yellowRect = new Kinetic.Rect({
width: yellowText.getWidth(),
height: yellowText.getHeight(),
fill: 'yellow',
stroke: 'black',
strokeWidth: 4
});

blueGroup.add(blueRect).add(blueText);
yellowGroup.add(yellowRect).add(yellowText);

layer.add(blueGroup);
layer.add(yellowGroup);
stage.add(layer);

</script>
</head>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息