如何创建SVG游标跟踪元素?

时间:2013-04-06 03:27:08

标签: javascript animation javascript-events svg

我有以下XML代码来创建一个SVG图像,该图像有一个跟在用户光标周围的小圆圈。跟踪光标并显示圆圈的区域与图像的其余部分不对齐。我不知道为什么会这样。我希望有人能够启发我(几天前我刚开始学习SVG)。

如果我将preserveAspectRatioxMidYMin更改为none,则圈子会出现一组不同的问题。它不会跟随光标向下很远,它向右移动得比它应该更远。

另外,我对JavaScript不是很了解,所以如果你看到代码可以简化的方法,或者你可以弄清楚如何将其转换为jQuery,我将非常感激。

<?xml version="1.0" encoding="utf-8" standalone="no" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd" [ <!ATTLIST svg xmlns:a3 CDATA #IMPLIED a3:scriptImplementation CDATA #IMPLIED>
<!ATTLIST script a3:scriptImplementation CDATA #IMPLIED> ]>
<svg viewBox="0 0 720 1278" preserveAspectRatio="xMidYMin"
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink"
 xmlns:a3="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/"
 a3:scriptImplementation="Adobe"
 onload="init(evt)"
 onzoom="updateTracker(evt)"
 onscroll="updateTracker(evt)"
 onresize="updateTracker(evt)">
<script type="text/ecmascript" a3:scriptImplementation="Adobe">
<![CDATA[
  var elems = {
      tracker: false,
      cursor: false,
      trans: true,
      scale: true,
      mx: true,
      my: true,
      ux: true,
      uy: true
  };
  var frame = {
      x_trans: 0,
      y_trans: 0,
      zoom: 1,
      x_scale: 1,
      y_scale: 1
  };

  function init(e) {
      if (window.svgDocument == null) svgDocument = e.target.ownerDocument;
      // Find nodes by id and store in elems object
      for (var id in elems) getElement(id, elems[id]);
  }

  function getElement(id, useFirstChild) {
      // Find the node with the specified id
      var node = svgDocument.getElementById(id);
      if (useFirstChild) {
          // Grab first child of node
          // This is used to get the text node of tspan and text elements
          elems[id] = node.firstChild;
      } else {
          // Do not need first child so use the node we just found
          elems[id] = node;
      }
  }

  function updateTracker(e) {
      // Get the top-most SVG element
      var SVGRoot = svgDocument.documentElement;
      // Get the current zoom and pan settings
      var trans = SVGRoot.currentTranslate;
      var scale = SVGRoot.currentScale;
      // Determine the translation needed to move the upper-left
      // corner of our tracking rectangle to the upper-left of the
      // current view.
      // The zeros are used to reinforce that we are translating
      // the origin of the rectangle to the upper-left corner of the
      // current view.
      frame.x_trans = (0.0 - trans.x) / scale;
      frame.y_trans = (0.0 - trans.y) / scale;
      // Now that we have moved the rectangles corner to the
      // upper-left position, let us scale the rectangle to fit
      // the current view.  X and Y scales are maintained seperately
      // to handle possible anamorphic scaling from the viewBox
      frame.zoom = scale;
      frame.x_scale = 1 / scale;
      frame.y_scale = 1 / scale;
      // Get the current viewBox
      var vbox = SVGRoot.getAttributeNS(null, "viewBox");
      if (vbox) {
          // We have a viewBox so, update our translation and scale
          // to take the viewBox into account
          // Break the viewBox parameters into an array to make life easier
          var params = vbox.split(/\s+/);
          // Determine the scaling from the viewBox
          // Note that these calculations assume that the outermost
          // SVG element has height and width attributes set to 100%.
          var h_scale = window.innerWidth / params[2];
          var v_scale = window.innerHeight / params[3];
          // Update our previously calculated transform
          frame.x_trans = frame.x_trans / h_scale + parseFloat(params[0]);
          frame.y_trans = frame.y_trans / v_scale + parseFloat(params[0]);
          frame.x_scale = frame.x_scale / h_scale;
          frame.y_scale = frame.y_scale / v_scale;
      }
      // Apply changes to the tracking rectangle
      updateTrackerTransform();
  }

  function updateCursor(e) {
      // Get the mouse x and y coordinates
      var x = e.clientX;
      var y = e.clientY;
      // Calculate the user-coordinate using the scaling and
      // translation values we calculated for the tracking
      // rectangle
      var nx = x * frame.x_scale + frame.x_trans;
      var ny = y * frame.y_scale + frame.y_trans;
      // Update the cursor position
      elems.cursor.setAttributeNS(null, "cx", nx);
      elems.cursor.setAttributeNS(null, "cy", ny);
      // Update our text fields
      elems.mx.data = x;
      elems.my.data = y;
      elems.ux.data = nx;
      elems.uy.data = ny;
  }

  function updateTrackerTransform() {
      // Build the text versions of the translate and scale transformation
      var trans = "translate(" + frame.x_trans + "," + frame.y_trans + ")"
      var scale = "scale(" + 1 / frame.zoom + "," + 1 / frame.zoom + ")";
      // Apply the transformation to our tracking rectangle
      elems.tracker.setAttributeNS(null, "transform", trans + " " + scale);
      // Update our text fields
      elems.trans.data = trans;
      elems.scale.data = scale;  }]]>
</script>
<!-- Create the cursor element -->
<circle id="cursor" cx="100" cy="100" r="10" fill="orange" />
<!-- A group of elements collectively refered to as the tracker -->
<g id="tracker">
    <!-- Draw a visible rectangle to show the tracking area -->
    <rect x="0" y="0" width="100%" height="100%" fill="blue" opacity="0.25" />
    <!-- - This is the actual tracking rectangle. This is all that is needed - to track the cursor. Just place the "tracker" id here and remove this group - and all of the other elements in this group -->
    <rect x="0" y="0" width="100%" height="100%" opacity="0" onmousemove="updateCursor(evt)" />
</g>
</svg>

Live demo on jsFiddle

1 个答案:

答案 0 :(得分:1)

我偶然发现了这个解决方案。有没有更好的方法呢?

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 1278">
<title>This'll be Great</title>
<style>
    * { vector-effect:non-scaling-stroke }
    rect { fill: blue; }
    circle { fill:orange; opacity:0.75; }
</style>
<rect cx="50%" cy="0" width="720" height="1278" id="origin" />
<circle cx="50%" cy="116" r="72" id="dot"    />
<script>
    var svg  = document.documentElement,
        pt   = svg.createSVGPoint(),
        dot  = document.querySelector('#dot');

    svg.addEventListener('mousemove',function(evt){
      var loc = cursorPoint(evt);
        dot.setAttribute('cx',loc.x);
        dot.setAttribute('cy',loc.y);
    },false);

    function rotateElement(el,originX,originY,towardsX,towardsY){
        var degrees = Math.atan2(towardsY-originY,towardsX-originX)*180/Math.PI + 90;
        el.setAttribute(
            'transform',
            'translate('+originX+','+originY+') translate('+(-originX)+','+(-originY)+')'
        );
    }

    // Get point in global SVG space
    function cursorPoint(evt){
      pt.x = evt.clientX; pt.y = evt.clientY;
      return pt.matrixTransform(svg.getScreenCTM().inverse());
    }
</script> 
</svg>