2014-04-01 3 views
0

DIV 요소 인 "pageContainer1"이있는 iframe이 있습니다. 그 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. 당신이 때 이미 캔버스를 두 번째로 얻을 필요가 이유가있다 변수 "canvas"에 액세스 할 수 있습니까? 그것을 제거하고 작동하는지 확인하십시오.

  3. 시도 페이지를 검사하고이 도움이된다면 캔버스가 편집

추가 참조 된 것을 확인 :

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/

편집 2을 님이 html을 설정하는 대신 createElement를 사용하도록 피들을 업데이트했습니다.

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

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

"캔버스"에 대한 액세스 권한이 무엇을 의미합니까? 내 질문을 이해하지 못했다고 생각합니다. iframe에있는 DIV 요소에 캔버스를 추가하고 싶습니다. 그것을하는 방법? 어떤 제안. 위의 코드는 오류를 보여줍니다. can.appendChild (canvas)의 경우 "undefined가 함수가 아닙니다." – user3454558

관련 문제