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

Javascript:使用“捕获”捕获元素;getElementsByTagName";?,javascript,jquery,canvas,2d,Javascript,Jquery,Canvas,2d,我有一个javascript canavas代码,如果我捕捉到ID为的标记“Canvas”,它就会开始工作,但如果我使用“TagName”捕捉到它,它就会停止工作 在我的代码中,画布标记是在运行时生成的,我无法传递相同的ID,因此我希望通过使用标记名捕捉在画布上生成2D对象 以下是相同的代码: JS var canvas=document.getElementsByTagName("canvas"); var context=canvas.getContext("2d");

我有一个javascript canavas代码,如果我捕捉到ID为的标记“Canvas”,它就会开始工作,但如果我使用“TagName”捕捉到它,它就会停止工作

在我的代码中,画布标记是在运行时生成的,我无法传递相同的ID,因此我希望通过使用标记名捕捉在画布上生成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);
这是同样的小提琴:

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

请建议。

您需要更改

document.getElementsByTagName("canvas");
为此:

document.getElementsByTagName("canvas")[0];
这样,您将获得第一个元素(在本例中只有一个),而不是节点列表(没有
getContext
函数)

更好的替代方法实际上是在画布元素上使用ID,并使用类似于
getElementById(“canvas”)
的东西,这样您就可以确切地知道您使用的是什么元素(以防最终使用多个画布元素)


返回一个,而返回一个。请尝试
canvas[0]。getContext(“2d”)
返回canvas的第一个实例。

标题中不应出现“不工作”。明智地利用空间快速总结实际问题。如果问题中清楚地描述了问题,这将更容易做到。谢谢!!关于第二个选项,我同意使用“ID”总是更好,但正如我在问题中提到的,在我的实际代码中,Canvas是在运行时生成的,我无法在运行时传递ID,所以我正在寻找标记名的选项。。。但是很好的解释。。我今天学到了新东西!:-)我同意,当我更改为“canvas.getContext(“2d”)[0]”时,代码不起作用,但当我更改为“canvas[0].getContext(“2d”)时,代码起作用。。。但是谢谢你解释这个问题!