3

此代码有效:

<canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.beginPath();
      context.moveTo(0, 200);
      context.lineTo(578, 0);
      context.stroke();

      context.beginPath();
      context.moveTo(0, 0);
      context.lineTo(578, 200);
      context.stroke();
    </script>

我尝试在 jQuery 中做同样的事情,但没有奏效:

对象[对象对象]没有方法'getContext'

var context = $('.dropzone').getContext('2d');
context.beginPath();
context.moveTo(0, 200);
context.lineTo(578, 0);
context.stroke();

context.beginPath();
context.moveTo(0, 0);
context.lineTo(578, 200);
context.stroke();

我什至在stackoverflow上读到我应该试试这个(没用)

在代码中添加了[0]

" Object #<HTMLDivElement> 没有方法 'getContext' "

var context = $('.dropzone')[0].getContext('2d');

问题

我想在每个 .dropzone 中“绘画”。那不可能吗?如何?

4

3 回答 3

2

That is because you are using class in jquery.

Change this

var context = $('.dropzone').getContext('2d');

to

var context = $('#dropzone').getContext('2d');

于 2012-10-26T10:13:32.447 回答
2

Use .each()

$('.dropzone').each(function(index, element) {
    var context = element.getContext('2d');
    context.beginPath();
    context.moveTo(0, 200);
    context.lineTo(578, 0);
    context.stroke();

    context.beginPath();
    context.moveTo(0, 0);
    context.lineTo(578, 200);
    context.stroke();   
});

Here's an example on jsfiddle.

于 2012-10-26T10:13:50.787 回答
2

您需要使用.each()该类遍历所有元素。

$('.myCanvas').each(function() {
   var canvas = $(this)[0];
   var context = canvas.getContext('2d');
  // Do stuff
});

工作 JSFiddle

于 2012-10-26T10:16:24.420 回答