Javascript:使用 "getElementsByTagName"捕获元素?

标签 javascript jquery canvas 2d

我有一个 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);

这是相同的 fiddle :http://jsfiddle.net/Sg7EZ/179/

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

请提出建议。

最佳答案

你会想要改变

document.getElementsByTagName("canvas");

对此:

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

这样您将获得第一个元素(在本例中只有一个)而不是节点列表(它没有 getContext 函数)

JSFiddle

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

JSFiddle

关于Javascript:使用 "getElementsByTagName"捕获元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25557593/

相关文章:

javascript - HTML5 中的 localStorage 是如何工作的?

javascript - ReactJS 循环遍历集合

javascript - 删除/阻止将来的元素加载到 DOM 中

css - Jcrop - 可裁剪区域和图像大小的问题

动态选项卡中的 Javascript 计算总计

javascript - 如何从返回 document.write() 的 URL 异步显示数据?

android - 带有视频源的 HTML5 Canvas drawImage 不适用于 Android

javascript - 将图像拖放到 Canvas 上后允许拖动

jquery - 带有 href 的多个随机 img

javascript - 如何使用 Ajax 将变量从 PHP 发送到 javascript?