Canvas循环类元素TypeError:$ this.getContext不是函数

时间:2014-01-10 09:19:57

标签: javascript canvas html5-canvas

我不知道为什么有错误我使代码像这样: http://jsfiddle.net/kMN3s/2/。 这是我网站上的分拣机。我想让画布按钮看起来像箭头。

HTML:

<div id="sortbtn">
      <a href="#" class="top" date-color-arrow="#FF0000"><canvas class="arrowup"></canvas></a>
      <a href="#" date-color-arrow="#000000"><canvas class="arrowdown"></canvas></a>
      <a href="#" class="top" date-color-arrow="#000000"><canvas class="arrowup"></canvas></a>
      <a href="#" date-color-arrow="#000000"><canvas class="arrowdown"></canvas></a>
</div>

使用Javascript:

        $('#sortMm a').each(function () {
            $this = $(this).find('canvas');
            var colorArrow = $(this).attr('date-color-arrow');
            var stanceArrow = this.getElementsByClassName('top');
            if (stanceArrow == true) {
                var arrowtop = $this.getContext("2d");
                arrowtop.fillStyle = colorArrow;
                arrowtop.beginPath();
                arrowtop.moveTo(5, 0);
                arrowtop.lineTo(9, 5);
                arrowtop.lineTo(0, 5);
                arrowtop.lineTo(5, 0);
                arrowtop.closePath();
                arrowtop.fill();
            } else {
                var arrowbottom = $this.getContext("2d");
                arrowbottom.fillStyle = colorArrow;
                arrowbottom.beginPath();
                arrowbottom.moveTo(5, 5);
                arrowbottom.lineTo(0, 0);
                arrowbottom.lineTo(9, 0);
                arrowbottom.lineTo(5, 5);
                arrowtop.closePath();
                arrowbottom.fill();
            }
        });

2 个答案:

答案 0 :(得分:1)

试试这个

$(this).find("canvas").get(0).getContext("2d");

答案 1 :(得分:0)

您不能在jQuery对象上使用.getContext()。您更需要“底层”DOM对象。这可以通过在jQuery对象上使用[0]数组索引来实现。

$('#sortMm a').each(function () {
        var canvas = $(this).find('canvas')[0];
        var colorArrow = $(this).attr('date-color-arrow');
        var stanceArrow = this.getElementsByClassName('top');
        if (stanceArrow == true) {
            var arrowtop = canvas.getContext("2d");
            arrowtop.fillStyle = colorArrow;
            arrowtop.beginPath();
            arrowtop.moveTo(5, 0);
            arrowtop.lineTo(9, 5);
            arrowtop.lineTo(0, 5);
            arrowtop.lineTo(5, 0);
            arrowtop.closePath();
            arrowtop.fill();
        } else {
            var arrowbottom = canvas.getContext("2d");
            arrowbottom.fillStyle = colorArrow;
            arrowbottom.beginPath();
            arrowbottom.moveTo(5, 5);
            arrowbottom.lineTo(0, 0);
            arrowbottom.lineTo(9, 0);
            arrowbottom.lineTo(5, 5);
            arrowtop.closePath();
            arrowbottom.fill();
        }
});