【发布时间】:2016-11-16 10:15:20
【问题描述】:
我知道 SVG <g> 标签没有 X 和 Y 属性,传输它的唯一方法是使用 transform 像 transform="translate(x,y)" 和 transform="rotate(45 50 50)"
我正在尝试使用 JavaScript 执行相同的可编程操作,我想在其中移动具有 rect 和 text 组合的 g 标签,下面是我的代码,所以我犯了什么错误@ 987654329@点击后不移动/翻译?
var NS="http://www.w3.org/2000/svg";
var SVG=function(h,w){
var svg=document.createElementNS(NS,"svg");
svg.width=w;
svg.height=h;
return svg;
}
var svg=SVG(1200,1500);
document.body.appendChild(svg);
class myRect {
constructor(x,y,h,w,fill,name) {
this.g= document.createElementNS(NS,"g");
this.name=name;
this.SVGObj= document.createElementNS(NS,"rect");
self = this.SVGObj;
self.x.baseVal.value=x;
self.y.baseVal.value=y;
self.width.baseVal.value=w;
self.height.baseVal.value=h;
self.style.fill=fill;
this.text = document.createElementNS(NS, 'text');
this.text.setAttribute('x', x+10);
this.text.setAttribute('y', y+20);
this.text.setAttribute('fill', '#000');
this.text.textContent = '2';
this.g.appendChild(self);
this.g.appendChild(this.text)
this.g.addEventListener("click",this,false);
}
}
Object.defineProperty(myRect.prototype, "node", {
get: function node() {
return this.g; // this.SVGObj;
}
});
myRect.prototype.handleEvent= function(evt){
self = this.g;
switch (evt.type){
case "click":
// alert(this.name); // this.animate();
if (typeof self.moving == 'undefined' || self.moving == false) self.moving = true;
else self.moving = false;
if(self.moving == true)
self.move = setInterval(()=>this.animate(),100);
else{
clearInterval(self.move);
self.parentNode.removeChild(self);
}
break;
default:
break;
}
}
myRect.prototype.animate = function() {
self = this.g;
self.transform="translate(200,200)";
// self.x.baseVal.value+=1;
// self.y.baseVal.value+=1;
};
var r= new myRect(50,50,30,30,'#'+Math.round(0xffffff * Math.random()).toString(16),'this is my name');
svg.appendChild(r.node);
更新
我尝试了self.setAttribute('transform','translate(10,10)') 但没有用,我只能使用self.setAttribute('transform','translate(10,10)'); 进行一步一次移动,其中 getItem(0) 获取转换属性中的第一个元素,例如transform="translate(1, 1) scale(2)" 其中getItem(0) 得到translate(1, 1) 矩阵,getItem(1) 得到scale(2) 解释here
但这仍然不是我需要的,一旦我点击g 直到循环结束,我需要持续移动。
【问题讨论】:
标签: javascript svg translate-animation