2014-04-01 35 views
0

我有一個iframe中有DIV元素「pageContainer1」。我希望能夠在該DIV元素中添加一個畫布元素並訪問它以在其上繪製某些內容。我迄今爲止嘗試過,但似乎沒有工作。如何在iframe中創建畫布元素?

var can=document.getElementById('frame').contentWindow.document.getElementById("pageContainer1"); 

var canvas=document.createElement("canvas"); 
canvas.id="testcanvas"; 

can.appendChild(canvas); 
var can1=document.getElementById("frame").contentWindow.document.getElementById("testcanvas"); 
var ctx= can1.getContext('2d'); 

    ctx.beginPath(); 
    ctx.moveTo(20,20); 
    ctx.lineTo(100,100); 
    ctx.stroke(); 

請建議一些方法來做到這一點,即使通過使用jQuery。

回答

0
  1. 驗證iframe是滿載,並且你得到一個有效的元素早在變量「可以」

  2. 是存在的,爲什麼你需要你的時候就已經獲得畫布第二次的理由可以在變量「畫布」中訪問它?嘗試刪除它,看看它是否工作。

  3. 嘗試檢查網頁並確保畫布已添加

EDITED 看看這有助於:

function loaded() { 
    var iframe = document.getElementById('thisistheiframe'); 

    var iframediv = iframe.contentWindow.document; 

    iframediv.body.innerHTML += '<canvas id="thecanvas" style="background-color:red; width:100px; height:100px"></canvas>'; 

    var c = iframediv.getElementById('thecanvas'); 

    var ctx = c.getContext('2d'); 
    ctx.moveTo(20, 20); 
    ctx.lineTo(100, 100); 
    ctx.stroke(); 
} 

http://jsfiddle.net/mW8kv/

EDIT 2 更新小提琴使用createElement而不是隻是設置html:

var can = iframediv.createElement('canvas') 
can.id = 'thecanvas'; 
iframediv.body.appendChild(can); 

var c = iframediv.getElementById('thecanvas'); 
+0

你是什麼意思,我已經有權訪問「畫布」。我想你不明白我的問題。我想添加一個畫布在iframe中的DIV元素中。怎麼做?有什麼建議麼。上面的代碼顯示錯誤。「undefined不是函數」for line can.appendChild(canvas) – user3454558