js面向对象写法中使用requestAnimationFrame报错

js面向对象写法中使用requestAnimationFrame报错:

Failed to execute 'requestAnimationFrame' on 'Window': The callback provided as parameter 1 is not a function.*/

js:

    function parcicles() {
    var w = window.innerWidth;
    var h = window.innerHeight;
    this._w = w;
    this._h = h;
    this.pSize = Math.floor(Math.random() * 4);
    this.l = Math.random() * this._w;
    this.t = Math.random() * this._h;
    var r = Math.random() * 255 >> 0,
        g = Math.random() * 255 >> 0,
        b = Math.random() * 255 >> 0,
        a = Math.floor(Math.random() * 10);
    this.lineColor = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
}

parcicles.prototype = {
    emptyArray: [],
    length: 30,
    created: function () {
        for (var i = 0; i < this.length; i++) {
            this.emptyArray.push(new parcicles());
        }
    },
    createCanvas: function () {
        this.c = document.getElementById("c");
        this.ctx = this.c.getContext('2d');
        this.c.width = this._w;
        this.c.height = this._h;
    },
    draw: function () {
        console.log(1);
        for (var j = 0; j < this.length; j++) {
            this.ctx.beginPath();
            this.ctx.fillStyle = this.emptyArray[j].lineColor;
            this.ctx.arc(this.emptyArray[j].l, this.emptyArray[j].t, this.emptyArray[j].pSize, 0, Math.PI * 2, true);
            this.ctx.fill();
            this.ctx.closePath();
        }
    },
    move: function () {
        this.draw();
        requestAnimaFrame(this.move);
        // 上面的代码报错: Failed to execute 'requestAnimationFrame' on 'Window': The callback provided as parameter 1 is not a function.,了解但是不会修改 :[
    },
    init: function () {
        this.created();
        this.createCanvas();
        this.draw();
        this.move();
    }
}
var requestAnimaFrame = function (callback) {
    return window.requestAnimationFrame(callback) ||
        window.webkitRequestAnimationFrame(callback) ||
        window.mozRequestAnimationFrame(callback) ||
        window.oRequestAnimationFrame(callback) ||
        window.msRequestAnimationFrame(callback) ||
        function (callback) {
            setInterval(callback, 1000 / 60);
        }
};

var p = new parcicles();
p.init();

html:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Documenttitle>
    <link rel="stylesheet" href="css/canvas.css">
head>
<body>
    <canvas id="c">sorrycanvas>
    <script src="js/canvas.js">script>
body>
html>

请大神给解决下,问题知道出在哪里,就是不会改。因为传入的参数不是简单的函数名,但是面向对象的写法就要是this.draw()才能运行。求指点

  • 2017年02月20日提问
  • 评论
  • 邀请回答
  • 编辑
默认排序 时间排序

1个回答

答案对人有帮助,有参考价值 0 答案没帮助,是错误的答案,答非所问

已采纳

requestAnimaFrame(this.move);
改成
requestAnimaFrame(this.move.bind(this));
具体原因可以深入了解bind

你可能感兴趣的:(前端)