2014-08-28 33 views
-2

我有一個JavaScript的canavas代碼,如果我趕上帶有ID的標籤「畫布」,它開始工作,但如果我使用「標記名稱」它捕獲它停止工作。Javascript:使用「getElementsByTagName」捕獲元素?

在我的代碼中Canvas標籤是在運行時生成的,我無法傳遞相同的ID,所以我想通過使用tagname捕獲它在Canvas上生成2D對象。

下面是相同的代碼:

JS

var canvas=document.getElementsByTagName("canvas"); 
    var context=canvas.getContext("2d"); 

    function Line(x1,y1,x2,y2){ 
     this.x1=x1; 
     this.y1=y1; 
     this.x2=x2; 
     this.y2=y2; 
    } 
    Line.prototype.drawWithArrowheads=function(ctx){ 

     // arbitrary styling 
     ctx.strokeStyle="blue"; 
     ctx.fillStyle="blue"; 
     ctx.lineWidth=1; 

     // draw the line 
     ctx.beginPath(); 
     ctx.moveTo(this.x1,this.y1); 
     ctx.lineTo(this.x2,this.y2); 
     ctx.stroke(); 

     // draw the starting arrowhead 
     var startRadians=Math.atan((this.y2-this.y1)/(this.x2-this.x1)); 
     startRadians+=((this.x2>this.x1)?-90:90)*Math.PI/180; 
     this.drawArrowhead(ctx,this.x1,this.y1,startRadians); 
     // draw the ending arrowhead 
     var endRadians=Math.atan((this.y2-this.y1)/(this.x2-this.x1)); 
     endRadians+=((this.x2>this.x1)?90:-90)*Math.PI/180; 
     this.drawArrowhead(ctx,this.x2,this.y2,endRadians); 

    } 
    Line.prototype.drawArrowhead=function(ctx,x,y,radians){ 
     ctx.save(); 
     ctx.beginPath(); 
     ctx.translate(x,y); 
     ctx.rotate(radians); 
     ctx.moveTo(0,0); 
     ctx.lineTo(5,20); 
     ctx.lineTo(-5,20); 
     ctx.closePath(); 
     ctx.restore(); 
     ctx.fill(); 
    } 

    // create a new line object 
    var line=new Line(50,50,250,275); 
    // draw the line 
    line.drawWithArrowheads(context); 

這裏是相同的小提琴:http://jsfiddle.net/Sg7EZ/179/

讓我知道如果你需要的任何其他信息。

請建議。

+1

「不工作」不應出現在標題中。明智地使用空間來快速總結實際問題。如果在問題中清楚地描述了問題*,那麼做起來會容易得多。 – user2864740 2014-08-28 20:42:32

回答

3

你想改變

document.getElementsByTagName("canvas"); 

這樣:

document.getElementsByTagName("canvas")[0]; 

這樣你會得到的第一個元素(也是唯一一個在這種情況下),而不是節點列表(其沒有按「T具有getContext功能)

JSFiddle

更好的替代方案實際上是使用您的畫布元素上的ID並使用類似getElementById("canvas")的東西,以便確切知道您使用的是什麼元素(以防萬一您最終得到多個畫布元素)。

JSFiddle

+0

謝謝!關於第二個選項,我同意它總是更好地使用「ID」,但就像我在我的問題中提到的那樣,在我的實際代碼中,Canvas在運行時生成,我無法在運行時傳遞ID,所以我一直在尋找標籤名稱選項...但很好的解釋..今天我學到了新東西! :-) – UID 2014-08-28 20:54:39

2

getElementsByTagName返回NodeList,而getElementById返回Element。嘗試canvas[0].getContext("2d")返回畫布的第一個實例。

+1

我認爲你的意思是'canvas [0] .getContext(「2d」)' – smerny 2014-08-28 20:52:06

+0

我同意,當我更改爲「canvas.getContext(」2d「)[0]」時,代碼無效當我更改爲「canvas [0] .getContext(」2d「)」...但感謝您解釋問題! – UID 2014-08-28 20:58:55

+0

是的,謝謝你的糾正。 – 2014-08-28 21:08:09