本文介绍了HTML5 canvas jQuery getContext on classes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码的工作原理:

 < canvas id =myCanvaswidth =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中做同样的工作:



对象[object Object]没有方法'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上读,我应该尝试这strong>



向代码添加 [0]



Object#< HTMLDivElement>没有方法getContext。

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

问题



我想在每个.dropzone绘画。这不可能吗?如何?

解决方案

使用 .each()



< pre>< code> $('。dropzone')each(function(index,element){
var context = element.getContext );
context.beginPath();
context.moveTo(0,200);
context.lineTo(578,0);
context.stroke
$ b context.beginPath();
context.moveTo(0,0);
context.lineTo(578,200);
context.stroke();
});

这是一个。


This code works:

<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>

I tried to do the same in jQuery and that did not work:

"Object [object Object] has no method '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();

I even read on stackoverflow that I should try this (that did not work)

Added a [0] to the code.

"Object #<HTMLDivElement> has no method 'getContext'"

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

Question

I want to "paint" in every .dropzone. Is that not possible? How?

解决方案

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.

这篇关于HTML5 canvas jQuery getContext on classes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 21:21