我正在尝试对以下 html
元素进行动画处理,以实现类似于音量轮的功能。
<svg id="circle_svg" width="200" height="175">
<circle cx="100" cy="85" r="75" stroke="black" stroke-width="2" fill="lightgray"/>
<line id="line_alpha" x1="100" y1="85" x2="100" y2="160" style="stroke:rgb(0,0,255);stroke-width:2"/>
<circle id="dot_alpha" cx="100" cy="160" r="10" stroke="black" stroke-width="2" fill="red"/>
</svg>
基本思想是,单击红点并移动鼠标应导致以下行为:
- 红点沿着圆圈移动(即使鼠标没有完全停留在其上)。
- 圆上直线的终点位于红点后面。
- 页面其他位置显示的数字会随着 Angular 位移量而增加或减少。
我找到了demo online,允许在页面周围拖动 svg 圆圈,方法是将感兴趣的元素绑定(bind)到 mousedown 和 mouseup 事件并重写属性 cx和圆的 cy
到鼠标的当前位置。
但是,当使用我的示例(甚至使用原始代码)在 jsfiddle 上测试代码时,有些东西不起作用。您能看一下并就可能出现的问题给我建议吗?
最佳答案
我能够找到我的问题的解决方案(感谢 friend )并将其发布作为其他人的引用:
粘贴此代码的主要问题online demo jsfiddle
的一个问题是 JavaScript
库和函数的顺序是不可预测的。
因此,在定义绑定(bind)函数之前可能会调用某些绑定(bind)。 另外,演示中的代码比我需要的更复杂。
- 这是
jsfiddle
上的代码解决方案 - 下面是 SO 网站的工作片段
var dragging = false
var updateGraphics = function (e) {
if (dragging) {
var parentOffset = $('#wheel').offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
var cx = +$('#circle').attr('cx')
var cy = +$('#circle').attr('cy')
var r = +$('#circle').attr('r')
var dx = relX - cx
var dy = relY - cy
//var dx = e.clientX - cx
//var dy = e.clientY - cy
console.debug('cx: ' + cx);
console.debug('cy: ' + cy);
console.debug('dx: ' + dx);
console.debug('dy: ' + dy);
console.debug('clientX: ' + e.clientX);
console.debug('clientY: ' + e.clientY);
console.debug('relX: ' + relX);
console.debug('relY: ' + relY);
var a = Math.atan2(dy, dx)
var dotX = cx + r * Math.cos(a)
var dotY = cy + r * Math.sin(a)
$('#dot').attr('cx', dotX);
$('#dot').attr('cy', dotY);
$('#line_2').attr('x2', dotX);
$('#line_2').attr('y2', dotY);
}
}
$('svg').on('mousedown', function (e) {
dragging = true
updateGraphics(e)
})
$('svg').on('mouseup', function (e) {
dragging = false
})
$('svg').on('mousemove', updateGraphics)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg id="wheel" width="200" height="175" style="background-color:lightgreen;">
<circle id="circle" cx="100" cy="85" r="75" stroke="black" stroke-width="2" fill="lightgray"/>
<line id="line_1" x1="100" y1="85" x2="100" y2="160" stroke-dasharray="15,15" style="stroke:rgb(255,0,0);stroke-width:2"/>
<line id="line_2" x1="100" y1="85" x2="100" y2="160" style="stroke:rgb(0,0,255);stroke-width:2"/>
<circle id="dot" cx="100" cy="160" r="10" stroke="black" stroke-width="2" fill="red"/>
</svg>
关于javascript - 使用 Javascript 和 JQuery 对 svg 元素进行动画处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35026714/