Raphael js - 在组上动画不透明度,同时保留单个元素的不透明度

Raphael js - animate opacity on group while retaining individual elements opacities

本文关键字:不透明度 保留 单个 元素 Raphael 动画 js      更新时间:2023-09-26

如何在保持单个元素不透明度状态的同时,将一堆 Raphael 对象的不透明度作为对象进行动画处理?我无法在不影响每个元素的情况下在集合上制作动画,那么我如何创建一个对象来处理 - 我正在以 jQuery 的心态思考这是否有助于回答。

如果你保留全局变量,那么你可以这样做。看看演示

var p = new Raphael(10,10, 500, 500);
var x = 0.5;
var r = p.rect(20, 20, 100, 80, 5).attr({fill: 'red', opacity: x}),
    c = p.circle(200, 200, 80).attr({fill: 'orange'}),
    s = p.set(r, c);
s.click(function() {
    s[0].attr({opacity: x - 0.3});
    s[1].attr({opacity: 0.3});
});
适用于

任意数量的元素、任意数量的更改和任意数量的集合的一般解决方案是使用.customAttributes,它根据附加到该单个元素的值和集合的值计算和存储集合中每个元素的正确不透明度级别。

例如(在演示中,多次单击以查看三个圆圈的不透明度向一个方向更改,单击单个圆圈以另一种方式更改(:

http://jsbin.com/oxeyih/9/edit

使用这样的东西,它基本上将此功能添加到这个 Raphael 论文实例中的所有现有和未来的集合和元素中:

// apply this using .attr or .animate to sets or each in a set
// to set the opacity of the set as a whole, maintaining relative opacity
paper.customAttributes.setOpacity = function( setOpacity ){
  // elemOpacity might not be set yet
  if (typeof this.attr('elemOpacity') == 'undefined') {
    this.attr('elemOpacity', this.attr('opacity'));
  }
  return {opacity: setOpacity * this.attr('elemOpacity')};
}    
// apply this using .attr or .animate to indiviual elements
// to set that element's opacity, factoring in the opacity of the set
paper.customAttributes.elemOpacity = function( elemOpacity ){
  // setOpacity might not be set yet; setting it could create infinite loop
  var setOpacity = this.attr('setOpacity');
  setOpacity = typeof setOpacity == 'undefined' ? 1 : setOpacity;
  return {opacity: setOpacity * elemOpacity };
}

如果任一自定义属性低于 0.0 或高于 1.0,则代码可能出错,则可能需要添加某种验证。

任何时候你设置元素的不透明度,使用 animate({elemOpacity: xx}, time);(或.attr()(,它会考虑设置的不透明度,任何时候你想设置一个集合的不透明度,在集合上调用animate({setOpacity: xx}, time);,它会考虑每个元素的不透明度。


在某些情况下,对于复杂的集合,与其对许多元素进行动画处理,这在许多浏览器中可能会很慢,而是对性能更好,而且更简单,只是在上面叠加一个......如果相关元素可以安全地发送到.toBack()并且您不需要与它们进一步交互(单击、悬停(,这是一个好主意。

只需添加一个叠加矩形,设置为匹配容器元素的继承颜色(这是一种动态获取继承背景颜色的方法(,然后发送它设置.toBack(),并对该叠加层的不透明度进行动画处理。