svg元素的触发事件在另一个元素后面移动?

时间:2018-06-01 11:43:31

标签: javascript html svg svg.js

所需的输出例如:当红色蒙版矩形移动到其中一个“孔”后面时,孔需要更改填充(或其他一些attr)。

当moving_rect进入/离开孔元素区域时,是否可以添加某种触发事件?

在行动中: https://jsfiddle.net/qwertasyx/n9v7L95j/

此处也是片段:

var draw = SVG('myDrawing').size('100%',200);

var rect_group = draw.group()

//we dont want to see this
var background = rect_group.rect(200,150).center(250,100).fill('#000')
// we want too see through those 'holes'
var hole1 = rect_group.rect(40,40).center(290,70 ).fill('#fff')
var hole2 = rect_group.rect(40,40).center(290,130).fill('#fff')
var hole3 = rect_group.rect(40,40).center(220,70 ).fill('#fff')
var hole4 = rect_group.rect(40,40).center(220,130).fill('#fff')

// object that we see through the holes
var moving_rect = draw.rect(40,40).fill('red').center(250,100)

//mask obj 
var mask = draw.mask()
$('#mask').on('click',function(e){
	mask.add(rect_group)
  moving_rect.maskWith(mask)
})

$('#animate').on('click',function(e){    moving_rect.animate(250).move(160,40).animate(250).move(250,40).animate(250).move(300,80).animate(250).move(250,160).animate(250).center(250,100)
})
svg{
  border-style: solid;
  border-width: 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.5/svg.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- 
  Bootstrap docs: https://getbootstrap.com/docs
-->
<div class="container-fluid">
  <div class="row">
    <div class="col-12">
    <h5>Example svg -> click button for animation </h5><button id="mask" class="btn btn-primary">mask rect</button> <button id="animate" class="btn btn-primary">animate</button>
    </div>
  </div>
</div>
<div class="container-fluid">
  <div class="row">
    <div class="col-12">
      <div id="myDrawing"></div>
    </div>
  </div>
</div>
<hr>

1 个答案:

答案 0 :(得分:0)

所以我制作了一个解决方案,在每个动画步骤中检查其中一个矩形(孔)是否与移动的矩形相交。 如果检测到交叉点,则会更改“孔”的填充颜色。

    // animate()...
    .duringAll(function () {
        // get box of the rectangle
        var bbox = this.bbox()

        // intersection function. You should define it somewhere outside
        // instead of redefining every time
        var intersect = function(boxA, boxB) {
            return (boxA.x < boxB.x2 && boxA.x2 > boxB.x &&
            boxA.y < boxB.y2 && boxA.y2 > boxB.y) 
        }

        // go trough the boxes of every hole defined before
        boxes.forEach(function (el, index) {
            if(intersect(bbox, el)) {
                // change color of fill on intersection
                rects[index].fill('#555')
            } else {
                rects[index].fill('#fff')
            }
        })

    })

工作小提琴: https://jsfiddle.net/Fuzzy/n9v7L95j/5/

取而代之的是举办一场活动。你可以去:

this.fire('intersection', {index: index})

// then bind with
moving_rect.on('intersection', function (ev) {
    var index = ev.detail.index

    // do somthing
    rects[index].fill('#333')
})