I've been creating some HTML5 interactive learning project like the one at code academy. So now I have an ace editor on my page and i want whenever user type on the editor, the result will be displayed on the iframe i have on the same page. I've done that so now whenever the user type html and css code the result will appear synchronous on the iframe. But the problem is i try to make a color filled canvas which require javascript. I copy the code from canvas tutorial from w3shcool and the canvas did appear but it appears blank with no color. So far here's my code.

Here's the script i use to put the value of ace editor into iframe:

   <script>
   var editor = ace.edit("editor");
   editor.setTheme("ace/theme/twilight");
   editor.getSession().setMode("ace/mode/html");

    editor.getSession().on('change', function(e) {
    var x = editor.getValue();
    var iFrame =  document.getElementById('myframe');
    var iFrameBody;
    if ( iFrame.contentDocument ) 
    { // FF
        iFrameBody = iFrame.contentDocument.getElementsByTagName('html')[0];
    }
    else if ( iFrame.contentWindow ) 
    { // IE
        iFrameBody = iFrame.contentWindow.document.getElementsByTagName('html')[0];
    }
        iFrameBody.innerHTML = x;
    });

$("button").click(function(){

});
   </script>

And here's my iframe tag on html:

 <iframe id="myframe" name="listenMsg" frameborder="0" src="">

 </iframe>

And here's the canvas script i put on the Ace editor:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

   <script>

   var c=document.getElementById("myCanvas");
   var ctx=c.getContext("2d");
   ctx.font="30px Arial";
   ctx.fillText("Hello World",10,50);

   </script>

  </body>
  </html>

Your help would be appreciated

有帮助吗?

解决方案

Scripts are not evaluated when setting innerHTML, you eiter need to set data url with contents of the editor as a source of your iframe. Or find or script elements and call iFrame.contentWindow.eval(script.textContent) on each of them.

Also have a look at jsbin source code at https://github.com/jsbin/jsbin

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top