使用 Javascript 和 JQuery 动画 svg 元素

Animate svg elements with Javascript and JQuery

我正在尝试为以下 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>

基本思路是单击红点并四处移动鼠标会导致以下行为:

  1. 红点沿着圆圈移动(即使鼠标没有准确停留在上面)。
  2. 圆上直线的终点在红点之后。
  3. 页面中其他地方显示的数字随着 angular 位移量的增加或减少。

我在网上找到了一个 demo 允许在页面周围拖动一个 svg 圆圈,通过将感兴趣的元素绑定到 mousedownmouseup 事件并重写属性 cxcy的圆圈到鼠标当前位置。

然而,当使用我的示例(甚至使用原始代码)测试 jsfiddle 上的代码时,有些东西不起作用。您能否看一下并就可能出现的问题给我建议?

我找到了我的问题的解决方案(感谢一位朋友)并将post它作为其他人的参考:

将此 online demo 中的代码粘贴到 jsfiddle 的主要问题是 JavaScript 库和函数的顺序不可预测。

因此在定义绑定函数之前可能会调用一些绑定。 此外,演示中的代码比我需要的更复杂。

  • 这是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>