javascript - Canvas 到 svg 用动画翻译

标签 javascript svg html5-canvas

我一直在使用 JavaScript library制作动画天气符号。我现在正在做 the cloud symbol 的 SVG 版本,并想知道哪种方法可能是最好的。

所以我制作了云的跟踪/路径,静态 ( jsFiddle ) 和 basic rotation isn't the right effect因为原始云 ( in the js canvas animation ) 基本上有 5 条曲线,它们在转动时膨胀和收缩。

我想到的可能的做法:

  • 制作 5 个圆圈,使用破折号仅显示所需的圆弧,然后制作动画并扩展/收缩圆圈

  • 制作 5 sub-paths并以某种方式激活扩展和收缩

  • 使用5个animateMotion动画

有更好的逻辑吗?任何关于如何思考这种逻辑的建议都会很棒。

与上面的 jsFiddle 相同的示例,使用 SE 应用程序:

var skycons = new Skycons({
    "color": "black"
});
var canvas = document.querySelectorAll('canvas');
[].forEach.call(canvas, function (el) {
    skycons.add(el, el.dataset.icon);
});

skycons.play();
<script src="https://rawgit.com/darkskyapp/skycons/master/skycons.js"></script>
<div class="fe_forecast">
    <div class="fe_currently">
        <canvas id="fe_current_icon" data-icon="cloudy" width="160" height="160" style="width:120px; height:120px"></canvas>
    </div>
</div>

最佳答案

我被你提供的 svg 代码误导了:

我首先想到您的 Canvas 代码正在绘制一个 Path2d,带有 moveTo , arcToquadraticCurveTo为了与您的 svg 路径交互 d 很容易调整的方法属性,因为 Canvas 的路径命令与 SVG 的路径命令几乎相同。

但是,我想您是通过 InkScape 或 Illustrator 等软件将位图转换为矢量而获得当前 svg 代码的。

实际上,Skycons 代码所做的是绘制 5 个圆,同时执行 compositeOperation,因此只有不重叠的笔划可见。

这里我修改了代码,让它变得显而易见:

(function(global) {
  "use strict";

      var requestInterval = function(fn, delay) {
        var handle = {value: null};
        function loop() {
          handle.value = requestAnimationFrame(loop);
          fn();
        }
        loop();
        return handle;
      },
      cancelInterval = function(handle) {
        cancelAnimationFrame(handle.value);
      };

  var KEYFRAME = 500,
      STROKE = 0.08,
      TAU = 2.0 * Math.PI,
      TWO_OVER_SQRT_2 = 2.0 / Math.sqrt(2);

  function circle(ctx, x, y, r) {
    ctx.beginPath();
    ctx.arc(x, y, r, 0, TAU, false);
    ctx.stroke();
  }

  function puff(ctx, t, cx, cy, rx, ry, rmin, rmax) {
    var c = Math.cos(t * TAU),
        s = Math.sin(t * TAU);

    rmax -= rmin;

    circle(
      ctx,
      cx - s * rx,
      cy + c * ry + rmax * 0.5,
      rmin + (1 - c * 0.5) * rmax
    );
  }

  function puffs(ctx, t, cx, cy, rx, ry, rmin, rmax) {
    var i;
    for(i = 5; i--; )
      puff(ctx, t + i / 5, cx, cy, rx, ry, rmin, rmax);
  }

  function cloud(ctx, t, cx, cy, cw, s, color) {
    t /= 30000;

    var a = cw * 0.21,
        b = cw * 0.12,
        c = cw * 0.24,
        d = cw * 0.28;

    puffs(ctx, t, cx, cy, a, b, c, d);
    puffs(ctx, t, cx, cy, a, b, c - s, d - s);

  }

  var Skycons = function(opts) {
        this.list        = [];
        this.interval    = null;
        this.color       = opts && opts.color ? opts.color : "black";
        this.resizeClear = !!(opts && opts.resizeClear);
      };

  Skycons.CLOUDY = function(ctx, t, color) {
    var w = ctx.canvas.width,
        h = ctx.canvas.height,
        s = Math.min(w, h);
    cloud(ctx, t, w * 0.5, h * 0.5, s, s * STROKE, color);
  };


  Skycons.prototype = {
    _determineDrawingFunction: function(draw) {
      if(typeof draw === "string")
        draw = Skycons[draw.toUpperCase().replace(/-/g, "_")] || null;

      return draw;
    },
    add: function(el, draw) {
      var obj;

      if(typeof el === "string")
        el = document.getElementById(el);

      // Does nothing if canvas name doesn't exists
      if(el === null)
        return;

      draw = this._determineDrawingFunction(draw);

      // Does nothing if the draw function isn't actually a function
      if(typeof draw !== "function")
        return;

      obj = {
        element: el,
        context: el.getContext("2d"),
        drawing: draw
      };

      this.list.push(obj);
      this.draw(obj, KEYFRAME);
    },
    set: function(el, draw) {
      var i;

      if(typeof el === "string")
        el = document.getElementById(el);

      for(i = this.list.length; i--; )
        if(this.list[i].element === el) {
          this.list[i].drawing = this._determineDrawingFunction(draw);
          this.draw(this.list[i], KEYFRAME);
          return;
        }

      this.add(el, draw);
    },
    remove: function(el) {
      var i;

      if(typeof el === "string")
        el = document.getElementById(el);

      for(i = this.list.length; i--; )
        if(this.list[i].element === el) {
          this.list.splice(i, 1);
          return;
        }
    },
    draw: function(obj, time) {
      var canvas = obj.context.canvas;

      if(this.resizeClear)
        canvas.width = canvas.width;

      else
        obj.context.clearRect(0, 0, canvas.width, canvas.height);

      obj.drawing(obj.context, time, this.color);
    },
    play: function() {
      var self = this;

      this.pause();
      this.interval = requestInterval(function() {
        var now = Date.now(),
            i;

        for(i = self.list.length; i--; )
          self.draw(self.list[i], now);
      }, 1000 / 60);
    },
    pause: function() {
      var i;
      if(this.interval) {
        cancelInterval(this.interval);
        this.interval = null;
      }
    }
  };

  global.Skycons = Skycons;
}(this));
var skycons = new Skycons({
    "color": "black"
});
var canvas = document.querySelectorAll('canvas');
[].forEach.call(canvas, function (el) {
    skycons.add(el, el.dataset.icon);
});

skycons.play();
<canvas id="fe_current_icon" data-icon="cloudy" width="160" height="160" style="width:120px; height:120px"></canvas>

要重现相同的动画,您确实必须创建一个 <animationPath>为你的圈子,然后设置他们的keyPointskeyTimes分别。
浏览器仍然不支持 svg's compositing operations , 所以你必须使用 <clipPath>并声明两次你的圈子动画。

这是一个例子:

<svg version="1.1" id="svg" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="-30 -30 160 160" width=200 height=200>
  <defs>
    <style>
      circle {stroke: #000; stroke-width: 7px; fill: white;}
    </style>

    <path id="mainmotion" d="M15.5-3.9c13.2,0,23.9,7.4,23.9,16.5S28.7,29.2,15.5,29.2S-8.4,21.8-8.4,12.7S2.3-3.9,15.5-3.9"/>
	
	<g id="g">
	<circle id="c1" cx="37.7" cy="32.3" r="27.5">
        <animateMotion dur="6s" repeatCount="indefinite" calcMode="linear" keyPoints="0; 0.2; 0.4; 0.6; 0.8; 1" keyTimes="0; 0.2; 0.4; 0.6; 0.8; 1">
          <mpath xlink:href="#mainmotion" />
        </animateMotion>
      </circle>
      <circle id="c2" cx="37.7" cy="32.3" r="27.5">
        <animateMotion dur="6s" repeatCount="indefinite" calcMode="linear" keyPoints="0.2; 0.4; 0.6; 0.8; 1; 0; 0.2" keyTimes="0; 0.2; 0.4; 0.6; 0.8; 0.8; 1">
          <mpath xlink:href="#mainmotion" />
        </animateMotion>
      </circle>
      <circle id="c3" cx="37.7" cy="32.3" r="27.5">
        <animateMotion dur="6s" repeatCount="indefinite" calcMode="linear" keyPoints="0.4; 0.6; 0.8; 1; 0; 0.2; 0.4" keyTimes="0; 0.2; 0.4; 0.6; 0.6; 0.8; 1">
          <mpath xlink:href="#mainmotion" />
        </animateMotion>
      </circle>
      <circle id="c4" cx="37.7" cy="32.3" r="27.5">
        <animateMotion dur="6s" repeatCount="indefinite" calcMode="linear" keyPoints="0.6; 0.8; 1; 0; 0.2; 0.4; 0.6" keyTimes="0; 0.2; 0.4; 0.4; 0.6; 0.8; 1">
          <mpath xlink:href="#mainmotion" />
        </animateMotion>
      </circle>
      <circle id="c5" cx="37.7" cy="32.3" r="27.5">
        <animateMotion dur="6s" repeatCount="indefinite" calcMode="linear" keyPoints="0.8; 1; 0; 0.2; 0.4; 0.6; 0.8" keyTimes="0; 0.2; 0.2; 0.4; 0.6; 0.8; 1">
          <mpath xlink:href="#mainmotion" />
        </animateMotion>
      </circle>
    </g>
    <clipPath id="clip">
		<use xlink:href="#c1"/>
		<use xlink:href="#c2"/>
		<use xlink:href="#c3"/>
		<use xlink:href="#c4"/>
		<use xlink:href="#c5"/>
    </clipPath>
  </defs>
	<use xlink:href="#g"/>
	<rect x=0 y=0 width=160 height=160 clip-path="url(#clip)" fill="white" />
</svg>

关于javascript - Canvas 到 svg 用动画翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33668238/

相关文章:

javascript - 如何处理 svg 中的 <path> 笔划宽度变为零

javascript - 如何使用 CSS 在 HTML 中设置外部 SVG 颜色?

python - 使用 Python/PIL 读取 SVG 文件

javascript - 如何在我的绘图图像上重叠 Canvas 圆并设置事件坐标

javascript - 在 Javascript 中将 RGB 数组转换为 RGBA 数组的快速方法

javascript - 使用 .animate( {'height' :'toggle' }) 时出现奇怪的 IE8 问题

javascript - 在 React 中显示标题下方带有 "Show More"的内容预览

javascript - getJSON没有输出?

javascript - canvas.toDataURL() 不会改变图像质量。怎么会?

javascript - app.set ('port' , 8080) 与 Express.js 中的 app.listen(8080)