Javascript:使用“getElementsByTagName”捕获元素?

UID*_*UID 0 javascript jquery 2d canvas

我有一个 javascript canavas 代码,如果我用 ID 捕获标签“Canvas”,它就会开始工作,但是如果我使用“TagName”捕获它,它就会停止工作。

在我的代码中,Canvas 标记是在运行时生成的,我无法传递相同的 ID,因此我想通过使用标记名捕获它来在 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);
Run Code Online (Sandbox Code Playgroud)

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

如果您需要任何其他信息,请告诉我。

请建议。

Dal*_*las 6

你会想要改变

document.getElementsByTagName("canvas");
Run Code Online (Sandbox Code Playgroud)

对此:

document.getElementsByTagName("canvas")[0];
Run Code Online (Sandbox Code Playgroud)

这样你将得到第一个元素(在这种情况下只有一个)而不是节点列表(它没有getContext函数)

JSFiddle

更好的选择实际上是在你的画布元素上使用 ID 并使用类似的东西,getElementById("canvas")这样你就可以确切地知道你正在使用什么元素(以防你最终得到多个画布元素)。

JSFiddle