【问题标题】:UIWebview creating SVG 'on the fly'UIWebview '即时'创建 SVG
【发布时间】:2011-10-23 16:55:03
【问题描述】:

这是上一篇关于在 UIWebview 中操作 SVG 的文章的延续。更多背景信息请先看这里:UIWebview manipulating SVG 'on the fly'

现在我正在尝试在同一框架内动态创建 SVG。

我曾尝试在 Javascript 中使用 createElementNS 方法,但没有成功。

这是我失败的尝试:

NSString *string = @"var svgDocument=document.getElementById('circle').getSVGDocument();var shape=svgDocument.createElementNS('http://www.w3.org/2000/svg', 'greencircle');shape.setAttributeNS(null, 'cx', 25);shape.setAttributeNS(null, 'cy', 25);shape.setAttributeNS(null, 'r',  20);shape.setAttributeNS(null, 'fill', 'green');svgDocument.appendChild(shape);";
[webView stringByEvaluatingJavaScriptFromString:string];

有人可以给我看一个例子,说明如何使用与上述类似的方法创建一个简单的圆圈。或者,如果有更好的方法来动态创建 SVG 图形,那么我很想知道!

谢谢。

【问题讨论】:

    标签: iphone html ios uiwebview svg


    【解决方案1】:

    其实你已经差不多了。

    createElementNS 的第二个参数应该是您正在创建的元素的类型(圆圈)而不是标识符(绿色圆圈),例如

    var shape=svgDocument.createElementNS('http://www.w3.org/2000/svg', 'circle');
    

    您可以改为使用 setAttributeNS 设置 id。

    shape.setAttributeNS(null, 'id', 'greencircle');
    

    另外,附加到 svgDocument.documentElement 而不仅仅是 svgDocument,否则你会得到一个错误:

    svgDocument.documentElement.appendChild(shape);
    

    顺便说一句,如果您还不是快速测试所有这些东西的最佳方式,那就是在桌面上的 Chrome 或 Safari 中打开开发者工具。使事情更容易调试。

    因此,如果您正在使用earlier question about manipulating SVG 中提到的文件,您可以使用以下方法进行原型设计:

    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <title>SVG</title>
        <script>
        function make_circle() {
                // test new Javascript code here before compacting it
            var svgDocument=document.getElementById('circle').getSVGDocument();
            var shape=svgDocument.createElementNS('http://www.w3.org/2000/svg', 'circle');
            shape.setAttributeNS(null, 'id', 'greencircle');            
            shape.setAttributeNS(null, 'cx', 25);
            shape.setAttributeNS(null, 'cy', 25);
            shape.setAttributeNS(null, 'r',  20);
            shape.setAttributeNS(null, 'fill', 'green');
            svgDocument.documentElement.appendChild(shape);
        }
        </script>
      </head>
      <body>
        <!-- click on link to test the code -->
        <a onclick='make_circle();'>Change color</a>
        <object id="circle" data="circle.svg" width="250" height="250" type="image/svg+xml"/> 
      </body>
    </html>
    

    显然,您无法以这种方式测试任何触摸事件。 :(

    当您的 Javascript 变得越来越复杂时,如果有更好的方法,可能值得研究如何将所有内容保存在应用程序包中的单独 .js 文件中,然后通过创建和插入动态创建的标签将其加载到 webview使用 stringByEvaluatingJavaScriptFromString。

    【讨论】:

    • 你又来救援了!我知道我已经接近了,但如果没有调试器就无法排除故障。您建议使用桌面浏览器是非常明智的。现在你提到它似乎很明显。再次感谢尤安。你让我摆脱了很多压力。干杯!
    猜你喜欢
    • 1970-01-01
    • 2011-01-12
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    相关资源
    最近更新 更多