Не могу найти ошибку. Класс для Canvas
Создал собственный класс для элемента Canvas, но не работает, а ошибку найти не могу.
<!doctype html> <html> <head> <meta charset="UTF-8" /> <link rel="stylesheet" type="text/css" href="style.css"> <script src="jquery.js" type="text/javascript"></script> <title>Canvas Drag and Drop Test</title> </head> <body id="menu"> <canvas id="canvas"></canvas> </body> <script> console.clear(); if (!window.requestAnimationFrame) { window.requestAnimationFrame = (function () { return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback, element) { window.setTimeout(callback, 16.7); }; })(); } var Class = function (canvas_element) { this.canvas = canvas_element this.canvas.width = canvas_element.offsetWidth this.canvas.height = canvas_element.offsetHeight this.ctx = this.canvas.getContext("2d"); this.WIDTH = window.innerWidth; this.HEIGHT = window.innerHeight; var _class = function () { }; _class.fn = _class.prototype; _class.extend = function (prop) { for (var i in prop) { _class[i] = prop[i]; } }; _class.include = function (prop) { for (var i in prop) { _class.fn[i] = prop[i]; } }; return _class; }; var myClass = new Class(document.getElementById("canvas")); myClass.extend({ ClearStyle: function () { this.ctx.strokeStyle = "rgba(0,0,0,1)"; this.ctx.fillStyle = "rgba(0,0,0,1)"; this.ctx.lineWidth = 1; }, RECT: function (x, y, w, h) { this.ctx.beginPath(); this.ctx.rect(x, y, w, h); this.ctx.fill(); this.ctx.stroke(); }, DrawText: function (s, x, y) { this.ctx.textBaseline = "middle"; this.ctx.textAlign = "center"; this.ctx.strokeText(s, x, y); }, draw: function () { this.RECT(0, 0, this.canvas.width, this.canvas.height) }, animate: function () { requestAnimationFrame(this.animate); this.draw() } }); </script> </html> Что в нем не так? |
this.canvas = canvas_element this.canvas.width = canvas_element.offsetWidth this.canvas.height = canvas_element.offsetHeight this.ctx = this.canvas.getContext("2d"); this.WIDTH = window.innerWidth; this.HEIGHT = window.innerHeight; Зачем это, если ты дальше возвращаешь какую-то непонятную функцию _class? В результате всех этих свойств у нее не будет. Да и вообще как должно это работать то? И зачем засовывать скрипт после закрывающего тега body? |
делал основываясь на этом уроке:
console.clear(); // не вижу смысла объяснять ВСЕ про ООП в JS (к тому же сам знаю не все:D) // Если использовать функцию с оператором new, то она возвращает объект function createObject(name) { this.name = name || "default"; // тут this ссылается на будущий объект } var o1 = new createObject("object1"); // получим объект со свойством name == object1 // Следующий уровень var Class = function () { var _class = function () {}; // обертка для нашего будующего класса _class.fn = _class.prototype; // ссылка на прототип // эта функция расширяет сам класс, но не его экземпляры _class.extend = function (prop) { for(var i in prop) { _class[i] = prop[i]; } }; // эта функция будет расширять экземпляры класса _class.include = function (prop) { for(var i in prop) { _class.fn[i] = prop[i]; } }; return _class; // возвращаем именно функция-обертку для создания уже экземпляров }; // Ну, с богом! var myClass = new Class(); // создали класс, теперь добавить свойств к экземплярам класса // У всех экземпляров будет свойство parent ( класс который создал экземпляр, просто строка, а не сссылка) myClass.include({ class : "parent", greet : function () { alert("hello, world"); } }); // Расширим сам класс myClass.extend({ someFunc : function () { alert("This is function of class"); } // "бездушная" функция }); // Попробуем создать класс и проверить его свойства var example = new myClass(); console.log(example); // все свойства, который мы указали в include есть! // так же работают свойства самого класса console.log(myClass.someFunc); // просто выведем, не будем вызывать // теперь можно плодить кучу объектов, с помощью нашего класса, при этом создавать новые классы, при этом расширять и делать каждый неповторимым var objects = []; for(var i = 0; i < 4; i++) { objects[i] = new myClass(); } console.log(objects); // Урок окончен, если что, потом могу рассказать как добавить настраиваемые экземпляры + наследование классов и прочие фишки из оригинального ООП // Ссылка на сам класс находится в this; myClass.extend({ showGreet : function () { // функция обращается к другой функции, которая уже является свойством класса, через this console.log(this.someFunc); } }); // Теперь используем нашу функцию myClass.showGreet(); // показывает нам функцию этого же класса // Навешаем обработчик var span = document.getElementById("sp"); span.onclick = (function () { return function () { alert(this.tagName); }.bind(span); })(); |
Сделал вот так, все заработало, но осталась маленькая ошибка.
console.clear(); if (!window.requestAnimationFrame) { window.requestAnimationFrame = (function () { return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback, element) { window.setTimeout(callback, 16.7); }; })(); } var Class = function () { var _class = function () { }; _class.fn = _class.prototype; _class.extend = function (prop) { for (var i in prop) { _class[i] = prop[i]; } }; _class.include = function (prop) { for (var i in prop) { _class.fn[i] = prop[i]; } }; return _class; }; var myClass = new Class(); myClass.extend({ init: function (canvas_element) { this.canvas = canvas_element this.canvas.width = canvas_element.offsetWidth this.canvas.height = canvas_element.offsetHeight this.ctx = this.canvas.getContext("2d"); this.WIDTH = window.innerWidth this.HEIGHT = window.innerHeight this.animate() }, ClearStyle: function () { this.ctx.strokeStyle = "rgba(0,0,0,1)"; this.ctx.fillStyle = "rgba(0,0,0,1)"; this.ctx.lineWidth = 1; }, RECT: function (x, y, w, h) { this.ctx.beginPath(); this.ctx.rect(x, y, w, h); this.ctx.fill(); this.ctx.stroke(); }, DrawText: function (s, x, y) { this.ctx.textBaseline = "middle"; this.ctx.textAlign = "center"; this.ctx.strokeText(s, x, y); }, draw: function () { this.RECT(0, 0, 100, 100) }, animate: function () { console.log("was here 1") requestAnimationFrame(this.animate); this.draw() } }); myClass.init(document.getElementById("canvas")) браузер ругается и выдает: Uncaught TypeError: Failed to execute 'requestAnimationFrame' on 'Window': The callback provided as parameter 1 is not a function.testClass.html:83 myClass.extend.animate |
Все исправил, ошибка была тут:
requestAnimationFrame(this.animate); нужно просто requestAnimationFrame(this); |
Часовой пояс GMT +3, время: 15:52. |