2010-08-22 215 views
2

这种东西卡住了,这就是为什么需要帮助。我正在使用HTML5和JavaScript在图像上插入文本,并使用文本创建新图像。如果我手动添加文本,一切都很好,但如果我试图将文本作为值传递给函数,则不会发生。这里的下面JavaScript,将值传递给函数

function draw_text(topt,bott){ 
    var canvas = document.getElementById("e"); 
    var context = canvas.getContext("2d"); 
    var img = new Image(); 
    img.src = "testimage.jpg"; 
    img.onload = function() 
    { 
    context.drawImage(img, 0, 0); 
    draw_text(); 
    }; 
    var toptext = this.topt; 
    var bottomtext = this.bott; 
    context.font = "12px Arial"; 
    context.fillStyle = "white"; 
    context.strokeStyle = 'black'; 
    context.fillText(toptext, (img.width-context.measureText(toptext).width)/2, 40); 
    context.strokeText(toptext, (img.width-context.measureText(toptext).width)/2, 40); 
    context.fillText(bottomtext, (img.width-context.measureText(bottomtext).width)/2, 350); 
    }; 

功能代码,我被

draw_text('Text 1','Text 2'); 

调用此函数,但我要么在画布上是完全不可见或者它带有文本“未定义”。我究竟做错了什么?顺便说一句,如果它是重要的,我正在codeigniter视图文件中执行此代码。

回答

3

您没有正确使用'this'。

替换:

var toptext = this.topt; 
var bottomtext = this.bott; 

有了:

var toptext = topt; 
var bottomtext = bott; 

***另外,我只注意到你有一个递归调用 “draw_text()” 不带参数的draw_text的定义,这也是一个问题。

+0

其实这是我第一次尝试的方式。没有工作!两种方式我都得到相同的结果。但是,如果我手动为topt和bott赋值,并像函数draw_text()那样对函数进行编码,它就会起作用。 – user427357 2010-08-22 00:36:30

+0

好吧,使用'这'是你绝对不会工作的方式。如果通过“draw_text('asd','asd')”而不是“draw_text(somevar,somevar2)”来调用函数,那么您传入的两个变量之一就是空或未定义的。 – jdc0589 2010-08-22 00:45:43

+0

另外,检查编辑我原来的答案 – jdc0589 2010-08-22 00:47:46