背景图像上有 svg。 SVG 是一个中间有圆孔的正方形(作为示例)。背景图像穿过圆圈出现。
我想用鼠标拖动这个圆圈。但如何从 javascript 访问 svg 内的 defs 尚不清楚。我可以更改属性,但 onclick 事件对它们不起作用。
这是我的 SVG,我想使用以下命令访问元素上的鼠标事件id = my_mask
:
<svg>
<defs>
<mask id="hole">
<rect width="100%" height="100%" fill="#fff"/>
<g id="my_mask">
<circle r="50" cx="100" cy="100" fill="#000"/>
</g>
</mask>
</defs>
<rect fill="#00f" width="100%" height="100%" mask="url(#hole)" />
</svg>
On mousemove
你重置了cx
and cy
圆的属性。我希望这就是你所问的。
//on `mousemove` you reset the `cx` and `cy` attributes of the circle
svg.addEventListener("mousemove",(e)=>{
let m = oMousePosSVG(e)
c.setAttributeNS(null,"cx",m.x)
c.setAttributeNS(null,"cy",m.y)
})
// a function to get the position of the mouse over the svg canvas
function oMousePosSVG(e) {
var p = svg.createSVGPoint();
p.x = e.clientX;
p.y = e.clientY;
var ctm = svg.getScreenCTM().inverse();
var p = p.matrixTransform(ctm);
return p;
}
svg{background:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/darwin300.jpg); background-size:cover}
<svg id="svg" viewBox="0 0 300 300">
<defs>
<mask id="hole">
<rect width="100%" height="100%" fill="#fff"/>
<g id="my_mask">
<circle id="c" r="50" cx="100" cy="100" fill="#000"/>
</g>
</mask>
</defs>
<rect fill="#00f" width="100%" height="100%" mask="url(#hole)" />
</svg>
UPDATE
您无法将事件附加到蒙版,但是您可以使用蒙版内的圆圈并将事件附加到使用,就像我在下一个示例中所做的那样:
在这个例子中我使用的是mousedown
事件,但你可以使用mouseover
反而。
let m,dx,dy;
let dragging = false;
theUse.addEventListener("mousedown",(e)=>{
m = oMousePosSVG(e);
dx = Number(c.getAttribute("cx")) - m.x;
dy = Number(c.getAttribute("cy")) - m.y;
dragging = true;
})
svg.addEventListener("mouseup",(e)=>{
dragging = false;
})
svg.addEventListener("mousemove",(e)=>{
if(dragging){
m = oMousePosSVG(e)
c.setAttributeNS(null,"cx",m.x + dx)
c.setAttributeNS(null,"cy",m.y + dy)
}
})
function oMousePosSVG(e) {
var p = svg.createSVGPoint();
p.x = e.clientX;
p.y = e.clientY;
var ctm = svg.getScreenCTM().inverse();
var p = p.matrixTransform(ctm);
return p;
}
svg{background:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/darwin300.jpg); background-size:cover}
<svg id="svg" viewBox="0 0 300 300">
<defs>
<mask id="hole">
<rect width="100%" height="100%" fill="#fff"/>
<g id="my_mask">
<circle id="c" r="50" cx="100" cy="100" />
</g>
</mask>
</defs>
<rect fill="#00f" width="100%" height="100%" mask="url(#hole)" />
<use id="theUse" xlink:href="#c" fill="none" pointer-events="all" />
</svg>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)