我有一個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/
讓我知道如果你需要的任何其他信息。
請建議。
「不工作」不應出現在標題中。明智地使用空間來快速總結實際問題。如果在問題中清楚地描述了問題*,那麼做起來會容易得多。 – user2864740 2014-08-28 20:42:32