getContext模糊效果,无法找到this.prev(' canvas')?

时间:2017-10-18 04:12:26

标签: javascript jquery canvas

HTML:

<div class="span">
      <canvas></canvas>
      <video autoplay loop muted onloadeddata="loaded(this)">
        <source src="xxx.mp4" type="video/mp4">
      </video>
</div>
<div class="span">
      <canvas></canvas>
      <video autoplay loop muted onloadeddata="loaded(this)">
        <source src="yyy.mp4" type="video/mp4">
      </video>
</div>

JS:

function draw(v, c, w, h) {
    if (v.paused || v.ended) return false;
    c.drawImage(v, 0, 0, w, h);
    setTimeout(draw, 1, v, c, w, h);
};
function loaded(vid) {
    $(vid).on('play', function() {
      var $this = $(vid).prev('canvas'),//this one dont work?
         $this = $('canvas').get(0),//i dont want this get(x), i need "this"
         cw = Math.floor($this.clientWidth / 1),
         ch = Math.floor($this.clientHeight / 1);
      $this.width = cw;
      $this.height = ch;
      draw(this, $this.getContext("2d"), cw, ch);
    });
};

为什么我找不到&#34;这&#34; ???

$ this = $(vid).prev(&#39; canvas&#39;),//这个不行?

$ this = $(&#39; canvas&#39;)。get(0),//我不想要这个得到(x),我需要&#34;这个&#34;

谢谢你,帮我解决这个问题: https://codepen.io/anon/pen/YrJqwQ

2 个答案:

答案 0 :(得分:0)

问题从这一行开始:

<video autoplay loop muted onloadeddata="loaded(this)">

this这里指的是窗口对象,而不是video元素。

解决它的一个解决方案如下:

HTML:

<div class="span">
      <canvas></canvas>
      <!-- remove "this" here because it won't be used -->
      <video autoplay loop muted onloadeddata="loaded()">
        <source src="xxx.mp4" type="video/mp4">
      </video>
</div>
<div class="span">
      <canvas></canvas>
      <!-- remove "this" here because it won't be used -->
      <video autoplay loop muted onloadeddata="loaded()">
        <source src="yyy.mp4" type="video/mp4">
      </video>
</div>

JS:

function draw(v, c, w, h) {
    if (v.paused || v.ended) return false;
    c.drawImage(v, 0, 0, w, h);
    setTimeout(draw, 1, v, c, w, h);
};

/*
Instead of "vid" argument use "this" keyword. 
"this" will refer to video element here.
*/
function loaded() {
    $(this).on('play', function() {
      var $this = $(this).prev('canvas'),//this one dont work?
         $this = $('canvas').get(0),//i dont want this get(x), i need "this"
         cw = Math.floor($this.clientWidth / 1),
         ch = Math.floor($this.clientHeight / 1);
      $this.width = cw;
      $this.height = ch;
      draw(this, $this.getContext("2d"), cw, ch);
    });
};

答案 1 :(得分:0)

prev()返回一个jQuery对象。您需要的是获取可以使用$(vid).prev('canvas').get(0)$(this).prev('canvas').get(0)

执行的canvas元素

e.g。

function loaded(vid) {
    $(vid).on('play', function() {
      var canvas = $(this).prev('canvas').get(0);
      cw = Math.floor(canvas.clientWidth / 1),
      ch = Math.floor(canvas.clientHeight / 1);
      canvas.width = cw;
      canvas.height = ch;
      draw(this, canvas.getContext("2d"), cw, ch);
    });
};