我想在悬停时更改 svg 元素的比例。
我的实际问题是当我将鼠标悬停在该元素上时,它会缩放但会改变位置。
我试图将我的路径分组到 g
元素中,但这也不起作用。
如何在不改变位置的情况下缩放 path
或 g
元素?
let svg= document.getElementsByTagName('svg')[0]
let newpath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
let newpath2 = document.createElementNS('http://www.w3.org/2000/svg', 'path');
let circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
let trainsPathallg = document.createElementNS('http://www.w3.org/2000/svg', 'g');
trainsPathallg.setAttribute('id','trainsPath')
let newpathg = document.createElementNS('http://www.w3.org/2000/svg', 'g');
newpath.setAttribute('d', 'M0,-10 V10 L10,0 Z');
newpath2.setAttribute('d', 'M0,0 L10,-10 V10 Z');
let progress=50;
let progress2= 300
let progress3= 400
let position = document.getElementById('s3')
let pt1 = position.getPointAtLength(progress);
let pt2 = position.getPointAtLength(progress + 0.1);
let a = (Math.atan2(pt2.y - pt1.y, pt2.x - pt1.x) * 180) / Math.PI;
newpath.setAttribute('transform', `translate(${pt1.x},${pt1.y})rotate(${a})`);
svg.appendChild(trainsPathallg)
trainsPathallg.appendChild(newpathg)
newpathg.appendChild(newpath);
#trainsPath > g:hover {
transform: scale(1.5);
//transform-origin: 50% 50%;
}
<svg viewBox = "0 0 800 300" version = "1.1">
<path id = "s3" d = "M10.51,27.68c202.42,340.08,200.57-4.6,300,15.67" fill = "none" stroke = "green" stroke-width = "3"/>
</svg>
最佳答案
您可以尝试将 transform-origin 与 transform-box: fill-box;
& animation
结合使用。
let svg = document.getElementsByTagName('svg')[0]
let newpath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
let newpath2 = document.createElementNS('http://www.w3.org/2000/svg', 'path');
let circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
let trainsPathallg = document.createElementNS('http://www.w3.org/2000/svg', 'g');
trainsPathallg.setAttribute('id', 'trainsPath')
let newpathg = document.createElementNS('http://www.w3.org/2000/svg', 'g');
newpath.setAttribute('d', 'M0,-10 V10 L10,0 Z');
newpath2.setAttribute('d', 'M0,0 L10,-10 V10 Z');
let progress = 50;
let progress2 = 300
let progress3 = 400
let position = document.getElementById('s3')
let pt1 = position.getPointAtLength(progress);
let pt2 = position.getPointAtLength(progress + 0.1);
let a = (Math.atan2(pt2.y - pt1.y, pt2.x - pt1.x) * 180) / Math.PI;
newpath.setAttribute('transform', `translate(${pt1.x},${pt1.y})rotate(${a})`);
svg.appendChild(trainsPathallg)
trainsPathallg.appendChild(newpathg)
newpathg.appendChild(newpath);
#trainsPath>g:hover {
transform: scale(1.5);
transform-origin: 50% 50%;
transform-box: fill-box;
}
#trainsPath g {
transition: transform .2s;
transform-origin: 50% 50%;
transform-box: fill-box;
}
<svg viewBox="0 0 800 300" version="1.1">
<path id = "s3" d = "M10.51,27.68c202.42,340.08,200.57-4.6,300,15.67" fill = "none" stroke = "green" stroke-width = "3"/>
</svg>
关于javascript - Svg 元素在悬停时改变位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58115876/