如何在iframe中创建canvas元素?

时间:2014-04-01 12:51:05

标签: javascript jquery iframe html5-canvas

我有一个iframe,其中有DIV元素" pageContainer1"。我希望能够在该DIV元素中添加canvas元素并访问它以在其上绘制内容。到目前为止,我已经尝试了这一点,但似乎无法发挥作用。

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也是如此。

1 个答案:

答案 0 :(得分:0)

  1. 验证iframe已完全加载,并且您在变量中获得了有效元素"可以"

  2. 当你已经在变量" canvas"?中访问它时,你需要第二次获得画布是有原因的吗?尝试删除它,看看它是否有效。

  3. 尝试检查页面并确保已添加画布

  4. <强> 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/

    编辑2 更新小提琴使用createElement而不是仅设置html:

    var can = iframediv.createElement('canvas')
    can.id = 'thecanvas';
    iframediv.body.appendChild(can);
    
    var c = iframediv.getElementById('thecanvas');
    
相关问题