iphone - UIWebview 创建 SVG 'on the fly'

标签 iphone html ios uiwebview svg

这是上一篇关于在 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 图形那么我很想知道!

谢谢。

最佳答案

其实你已经差不多了。

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 中提到的文件您可以使用以下方式进行原型(prototype)设计:

<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 文件中,然后通过创建和插入动态创建的标签将其加载到 Web View 中使用 stringByEvaluatingJavaScriptFromString。

关于iphone - UIWebview 创建 SVG 'on the fly',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7004803/

相关文章:

ios - 在 Visual Studio Tools for Apache Cordova 上设置 iPhone 6 启动图像

iphone - 使用 iphone SDK 和 "/api/write "发布到 tumblr

html - 防止文本环绕 awesomefonts 图像

ios - 程序流程出错

iphone - 在 NSDocumentDirectory 和 UIScrollView 中删除

ios - 如何获得iOS的FFT FFT频率幅度结果?

javascript - 如何使用 css 或 jquery 隐藏第二和第四表行?

html - 在一页上排列非常大的图像和附加文本

ios - AVAudioPlayer第一次不能正确播放音频

ios - 如何将按钮放在 PageViewController 的底部?