我想仅在矩形的笔划上添加click事件,并避免在矩形内部单击。
以下是代码:
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
var rect = new Kinetic.Rect({
x: 239,
y: 75,
width: 100,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 4
});
rect.on('click', function () {
var fill = this.getFill() == 'red' ? '#00d00f' : 'red';
this.setFill(fill);
layer.draw();
});
layer.add(rect);
stage.add(layer);
和小提琴:jsfiddle.net/6N3PB/
答案 0 :(得分:3)
经过大量的研究后,我找到了解决问题的方法。使用fillStrokeShape(this)的状态可以在drawHitFunc()中使用strokeShape(this)。希望它对其他人也有帮助
答案如下:
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
var rect = new Kinetic.Rect({
x: 239,
y: 75,
width: 100,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
drawHitFunc: function (context) {
var width = this.getWidth(),
height = this.getHeight();
context.beginPath();
context.rect(0, 0, width, height);
context.closePath();
context.strokeShape(this);
}
});
rect.on('click', function () {
var fill = this.getFill() == 'red' ? '#00d00f' : 'red';
this.setFill(fill);
layer.draw();
});
layer.add(rect);
stage.add(layer);
答案 1 :(得分:1)
创建一个包含描边矩形和填充矩形的组。
在描边矩形上侦听点击事件。
示例代码和小提琴:http://jsfiddle.net/m1erickson/MdwHA/
<!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 group=new Kinetic.Group({
x:20,
y:20,
draggable:true
});
layer.add(group);
var rectStroke = new Kinetic.Rect({
x:0,
y:0,
width:60,
height:40,
stroke: 'black',
strokeWidth: 10,
});
rectStroke.on("click",function(){
alert("clicked");
});
group.add(rectStroke);
var rectFill = new Kinetic.Rect({
x:0,
y:0,
width:60,
height:40,
fill: 'skyblue'
});
group.add(rectFill);
layer.draw();
}); // end $(function(){});
</script>
</head>
<body>
<h4>Click the rect stroke</h4>
<div id="container"></div>
</body>
</html>
[或者使用数学来消除填充]
演示:http://jsfiddle.net/m1erickson/RN3g9/
rect.on("click",function(){
var stroke=this.getStrokeWidth();
var x=this.getX()+stroke/2;
var y=this.getY()+stroke/2;
var w=this.getWidth()-stroke;
var h=this.getHeight()-stroke;
var pos=stage.getMousePosition();
var mx=pos.x;
var my=pos.y;
if(mx>x && mx<x+w && my>y && my<y+h ){return;}
alert("clicked");
});