javascript - js面向对象写法中使用requestAnimationFrame报错,求高手指点

查看:384
本文介绍了javascript - 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:

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

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

解决方案

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

这篇关于javascript - js面向对象写法中使用requestAnimationFrame报错,求高手指点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆