如何使用Jquery在script标签内动态添加画布

时间:2015-12-26 05:12:21

标签: javascript jquery html5 canvas

我有以下问题:我需要能够在.js文件中动态添加画布(确切地说,特定画布,如此https://web.chemdoodle.com/tutorial/2d-structure-canvases/sketcher-canvas/)但我的几次尝试都失败了。我想将画布插入<div id="sketcher_canvas"></div>。画布只能在脚本标签内创建,所以我也需要将脚本标签添加到HTML中。这是我的HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>ELN</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" src="//normalize-css.googlecode.com/svn/trunk/normalize.css" />
    <link href="{{url_for('static', filename='css/main.css')}}" rel='stylesheet' type='text/css'>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="{{url_for('static', filename='js/main2.js')}}"></script>
    <!-- ChemDoodle -->
    <link rel="stylesheet" href="{{url_for('static', filename='ChemDoodle/install/ChemDoodleWeb.css')}}" type="text/css">
    <script type="text/javascript" src="{{url_for('static', filename='ChemDoodle/install/ChemDoodleWeb.js')}}"></script>

    <!--these two are required by the SketcherCanvas plugin-->
    <link rel="stylesheet" href="{{ url_for('static', filename='ChemDoodle/install/uis/jquery-ui-1.10.3.custom.css')}}" type="text/css">
    <script type="text/javascript" src="{{url_for('static', filename='ChemDoodle/install/uis/ChemDoodleWeb-uis.js')}}"></script>
</head>

<body>        
      <script>    
          function make_canvas(){
            sketcher = new ChemDoodle.SketcherCanvas('sketcher',600,200);
          };
        </script>            

     <div id='sketcher_canvas'>

     </div>         

    <script        src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>   
</body>
</html>

这是我的.js:

$(document).ready(function(){
    // First option
    $('sketcher_canvas').append('<script>make_canvas();<\/script>);

    // Second option     
    var script   = document.createElement("script");
    script.type  = "text/javascript";
    script.text  = "make_canvas()";
    var div = document.getElementById('sketcher_canvas');
    div.innerHTML = script.text;
});

任何意见/建议都非常感谢!

1 个答案:

答案 0 :(得分:0)

看起来你正在制造比他们需要的更复杂的东西。您不需要创建新脚本来从另一个脚本调用函数。您可以使用如下按钮调用该函数:

        <script>    
          function make_canvas(){
             var newCanvas = document.createElement("canvas");
             newCanvas.id = "sketcher";
             newCanvas.class = "ChemDoodleWebComponent";
             document.getElementById("sketcher_canvas").appendChild(newCanvas);
            sketcher = new ChemDoodle.SketcherCanvas('sketcher',600,200);
          };
        </script>            
     <button onclick="make_canvas()">Make Canvas</button>
     <div id='sketcher_canvas'>

     </div>

编辑:我更新了make_canvas函数。您可以在此fiddle中查看其工作原理。