javascript - 一个 svg 元素在另一个元素后面移动的触发事件?
问题描述
例如,所需的输出是:当红色蒙版矩形在“孔”之一后面移动时,孔需要更改填充(或其他一些属性)。
是否可以添加某种在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>
解决方案
所以我一起制作了一个解决方案,在每个动画步骤中,检查一个矩形(孔)是否与移动的矩形相交。如果检测到交叉点,它会更改“孔”的填充颜色。
// 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')
})
推荐阅读
- node.js - Composer Rest 服务器错误“async *__getField() {”
- r - tidyverse 上下文中的 `~` 运算符是什么意思?
- python - 使用来自其他 kivy 类的条目
- date - 在 PySpark 中将一年中的一周转换为日期
- javascript - 一个正则表达式中 IP 和 MAC 地址的有效列表的正则表达式测试
- javascript - 出现错误:req.validatonErrors 不是函数,但我不知道为什么
- perl - 带有特殊字符的文件的 perl 取消链接失败
- php - 在 wordpress 中为自定义帖子类型定制多级 slug
- javascript - 选择日期范围选择器月份
- php - 带预览和删除选项的多图像上传 - Jquery /Php