0

需要一些关于解决这个问题的最佳方法的建议:

我已经疯狂地爱上了RaphaëlJS,因为它使 SVG 对我和我的编码变得可实现,因为它已经成功地将 IE 纳入其中。

但是,我不喜欢为.js要在页面上呈现的每个 SVG 图形都包含一个文件。

所以,我在互联网上四处寻找,看看我是否能找到更“动态”的东西,我发现了这个:(以下是我在这里找到的代码的编辑版本:http ://groups.google.com/组/raphaeljs/msg/ce59df3d01736a6f

function parseXML(xml) { 
  if (window.ActiveXObject && window.GetObject) { 
    var dom = new ActiveXObject('Microsoft.XMLDOM'); 
    dom.loadXML(xml); 
    return dom; 
  } 
  if (window.DOMParser) {
    return new DOMParser().parseFromString(xml, 'text/xml');
    throw new Error('No XML parser available');
  }
}

(function($) {

  $.fn.render_raphaels = function(options) {
    var defaults, options, counter, img_path, doc, root, vb, dims, img, node, path, atts, container, new_svg, inline;
    defaults = {};
    options = $.extend(defaults, options);

    counter = 0;
    inline = false;
    // find all the img's that point to SVGs
    $('img[src*="\.svg"]').each(function() {
      $(this).fadeOut(1000);
      img_path = $(this).attr('src');
      if (!$(this).attr('id')) new_svg = true;
      if ($(this).hasClass('inline')) inline = true;
      container = jQuery('<div/>', {
        id: $(this).attr('id') ? $(this).attr('id') : 'svg-' + (counter + 1),
        'class': $(this).attr('class') ? $(this).attr('class') : 'svg'
      }).hide().insertBefore($(this));

      $.get(img_path, null, function(doc) { 

        doc = parseXML(doc);
        root = $(doc).find('svg')[0];
        dims = [root.getAttribute('width'), root.getAttribute('height')];

        if(new_svg) container.css({ width: dims[0], height: dims[1] });
        if(inline) container.css('display', 'inline-block');

        img = Raphael(container.attr('id'), parseInt(dims[0]), parseInt(dims[1]));

        $(root).find('path').each(function() {
          node = this;
          path = img.path($(this).attr('d'));


          $(['stroke-linejoin','stroke','stroke-miterlimit','stroke-width','fill','stroke-linecap']).each(function() { 
            if($(node).attr(this.toString())) {
              path.attr(this, $(node).attr(this.toString()));
            } else {
              path.attr(this, 0);
            }
          });


          if($(node).attr('style')) {
            atts = $(node).attr('style').split(';');
            for(var i=0; i < atts.length; i++) { 
              bits = atts[i].split(':');
              path.attr(bits[0],bits[1]);
            }
          }

        });

      }, 'text');

      $(this).remove(); // removes the original image after the new one has been redrawn
      container.fadeIn(2000);
    });

  };

})(jQuery);

本质上,这让我可以只用.svg图形编写一个普通的图像标签,jQuery 插件会自动将其替换为 Raphaël 渲染的版本。

这在不兼容 SVG 的浏览器(如 IE)中效果很好,但在实际上已经支持 SVG 图形的现代浏览器中,图像标签按原样工作(没有 Raphaël),所以当 Raphaël 加载时,它会卸载现有图像,然后淡入Raphaël 版本……本质上是在制造闪烁。我试图通过淡入新版本来淡化这一点,但我仍然面临旧版本显示,被隐藏,然后再次显示的问题。

我需要一种方法来协调有问题的浏览器(如 IE)中的所需行为和现代、符合标准的浏览器(如 Safari 4 和 Firefox 3)中的不良行为。但是,我想以我没有的方式做到这一点显着改变我编码的方式(为什么我首先使用插件)。

我知道 SVG 仍然有点前沿,但有人对我如何解决这个问题有任何想法吗?

免责声明:如果可能的话,我想远离浏览器定位......我正在寻找一种可管理且功能强大的工作流解决方案,而不是浏览器黑客。

第二个免责声明:我不想要基于 Flash 的解决方案;我想尽可能地“原生”,我认为 javascript 比 Flash 更重要。(这就是为什么我对 Raphaël 如此兴奋,因为我可以远离 Flash)。

4

2 回答 2

0

你试过svgweb吗?

如果没有原生支持,将触发一个 flash 插件来渲染 SVG。

于 2010-01-26T08:06:58.067 回答
0

对,我想出了这个......(使用 Ruby on Rails,顺便说一句)

  1. 将 SVG 图形导出到public/images/svg/
  2. 运行rake svg:parse:to_json(下面是我的 rake 任务源)
  3. 使用 JSON 路径数据重绘 Raphaël 图形。
  4. 仅使用调用我的 SVG 图形<span class="svg">name_of_svg_file</span>(默认情况下使用 CSS 隐藏跨度并使用下面修改后的 jQuery 插件重绘)。

这意味着我从 Illustrator 到 HTML 的工作流程非常干净(我在 Capistrano 部署期间触发了我的 rake 任务)。这满足了我在问题中概述的需求,因为它可以在我迄今为止测试过的几乎所有浏览器(Raphaël 支持)中快速呈现且无闪烁,不需要 Flash,并且每个 SVG 只需编写一行代码图形(<span>带有图形名称的标签)。

欢迎重构。

ToDo:目前,如果用户关闭了javascript ,则没有替代品。我认为一个简单的<noscript>块可能会帮助我...


parse_svg.rake

require 'hpricot' # >= 0.8.2
require 'json/pure'

namespace :svg do
  namespace :parse do
    desc "Parse all SVG graphics in '/public/images/svg' into JSON libraries in '/public/javascripts/raphael/svg-js/' usable by Raphaël"
    task :to_json do
      FileList['public/images/svg/*.svg'].each do |svg|
        name = File.basename(svg).split('.')[0]
        doc = open(svg) { |f| Hpricot.XML(f) } # parse the SVG
        js = {} # container
        js[:name] = name
        js[:width] = doc.at('svg')['width'].to_i
        js[:height] = doc.at('svg')['height'].to_i
        js[:paths] = [] # all paths
        doc.search("/svg/g//path").each do |p|
          path = {} # our path hash
          path[:path] = p['d'].gsub(/(?:[\r\n\t])+/, ',')
          path[:stroke_width] = p['stroke-width'] || 0
          path[:stroke] = p['stroke'] || 0
          path[:fill] = p['fill'] || 0
          js[:paths] << path
        end
        File.open("public/javascripts/raphael/svg-js/#{name}.js", 'w') { |f| f.write(js.to_json) }
      end
      puts "Done!"
    end
  end
end

render_raphaels.jquery.js

(function($) {
  $.fn.render_raphaels = function(options) {
    var defaults, options, name, container, raphael;
    defaults = {
      span_id: 'svg-ref'
    };
    options = $.extend(defaults, options);
    // find all the spans that point to SVGs, based on default or passed-in identifier
    $('span.'+options.span_id).each(function() {
      name = $(this).text();
      $.getJSON('/javascripts/raphael/svg-js/' + name + '.js', function(data) {
        paper = Raphael(document.getElementById(data.name), data.width, data.height);
        for (var p in data.paths) {
          paper.path(data.paths[p].path).attr({
            fill: data.paths[p].fill,
            stroke: data.paths[p].stroke,
            'stroke-width': data.paths[p].stroke_width
          });
        }
      });
      // remove the span
      $(this).remove();
    });
  };
})(jQuery);

使用 SVG 调用所有页面

$.fn.render_raphaels({ span_id: 'svg' });
于 2010-01-28T18:39:30.810 回答