Lin*_*abo 5 javascript animation svg
我想通过变换矩阵(即时决定)来变换 SVG 画布上的元素。我可以使用 JQuery-SVG animate() 来做到这一点,但它的结果一点也不顺利。所以我想使用原生的SVG animateTransform,问题是:
先谢谢了
感谢您的回答!因为我想使用原生 SVG 动画,所以我找到了这个解决方案(仍然不能完美工作)。这是不存在的 animateTransform(attributeName="transform" type="matrix") 的一种版本
注意:我将每个元素的 svg 变换保留在 group.transform 中,而 group.transform.matrix() 仅返回该元素的变换矩阵。
我首先将这些元素添加到我想要设置动画的元素中:
<animateTransform id="canvTranslate" begin="indefinite" attributeName="transform" type="translate" to="" dur="1s" additive="sum" fill="freeze"/>
<animateTransform id="canvRotate" begin="indefinite" attributeName="transform" type="rotate" to="" dur="1s" additive="sum" fill="freeze"/>
<animateTransform id="canvScale" begin="indefinite" attributeName="transform" type="scale" to="" dur="1s" additive="sum" fill="freeze"/>
Run Code Online (Sandbox Code Playgroud)
然后我这样做:
var tMatrix = transformation.matrix(); //this is the transformation i want to obtain
var cMatrix = group.transform.matrix(); //this is the actual CTM of the element
//getting the animations
var animTrans = document.getElementById('canvTranslate');
var animRotaz = document.getElementById('canvRotate');
var animScale = document.getElementById('canvScale');
//setting duration (it's got somewhere before)
animTrans.setAttribute('dur', duration/1000+'s');
animRotaz.setAttribute('dur', duration/1000+'s');
animScale.setAttribute('dur', duration/1000+'s');
//calculating the 'from' attribute
var transX = cMatrix.e;
var transY = cMatrix.f;
var scaleX = Math.sqrt(Math.pow(cMatrix.a, 2)+Math.pow(cMatrix.b, 2));
var rotate = Math.atan(cMatrix.c/cMatrix.d);
animTrans.setAttribute('from', transX+','+transY);
animRotaz.setAttribute('from', -rotate*180/Math.PI);
animScale.setAttribute('from', scaleX);
//end 'from'
//calculating the 'to' attribute to set
var transX = tMatrix.e;
var transY = tMatrix.f;
var scaleX = Math.sqrt(Math.pow(tMatrix.a, 2)+Math.pow(tMatrix.b, 2));
var rotate = Math.atan(tMatrix.c/tMatrix.d);
animTrans.setAttribute('to', transX+','+transY);
animRotaz.setAttribute('to', -rotate*180/Math.PI);
animScale.setAttribute('to', scaleX);
//end 'to'
animTrans.beginElement();
animRotaz.beginElement();
animScale.beginElement();
Run Code Online (Sandbox Code Playgroud)
group.transform = transformation;最后,更新元素的转换属性:
setTimeout(function(){ //i will change this somehow better :)
//this is a problematic step. with it animations work on Chrome, without it they work good on firefox and opera too
$(group).attr('transform', 'matrix('+tMatrix.a+','+tMatrix.b+','+tMatrix.c+','+tMatrix.d+','+tMatrix.e+','+tMatrix.f+')');
}, duration+100);
Run Code Online (Sandbox Code Playgroud)
最后一步是有问题的。我不明白为什么它在 Chrome 中工作得很好,而动画最终在 Firefox 和 Opera 中缩放得更多(其中不调用 setTimeout 工作得很好)。