I would like to create a custom Raphael element, with custom properties and functions. This object must also contain predefined Raphael objects. For example, I would have a node class, that would contain a circle with text and some other elements inside it. The problem is to add this new object to a set. These demands are needed because non-Raphael objects cannot be added to sets. As a result, custom objects that can contain Raphael objects cannot be used. The code would look like this:
var Node = function (paper) {
// Coordinates & Dimensions
this.x = 0,
this.y = 0,
this.radius = 0,
this.draw = function () {
this.entireSet = paper.set();
var circle = paper.circle(this.x, this.y, this.radius);
this.circleObj = circle;
this.entireSet.push(circle);
var text = paper.text(this.x, this.y, this.text);
this.entireSet.push(text);
}
// other functions
}
var NodeList = function(paper){
this.nodes = paper.set(),
this.populateList = function(){
// in order to add a node to the set
// the object must be of type Raphael object
// otherwise the set will have no elements
this.nodes.push(// new node)
}
this.nextNode = function(){
// ...
}
this.previousNode = function(){
// ...
}
}
You can only add Raphael object (rect,circle, eclipse,text) to paper.set(), not self defined object( with Raphael.fn) . Instead use normal array definition of javascript [].
As fas as i understand nodeList is a simple list but with more options like nextnode , previous nodes.
Take a look at this demo, i changed abit José Manuel Cabrera's codes: http://jsfiddle.net/Tomen/JNPYN/1/
Raphael.fn.node = function(x, y, radius, txt) {
this.x = x;
this.y = y;
this.radius = radius;
this.txt = txt;
this.circleObj = paper.circle(this.x, this.y, radius), this.textObj = paper.text(this.x, this.y, this.txt);
this.entireSet = paper.set(this.circleObj, this.textObj);
return this
}
Raphael.fn.nodeList = function() {
this.nodes = [];
this.push = function(p) {
return this.nodes.push(p);
};
// this.nextNode = function(){
// ... manipulate this.nodes here
// }
// this.previousNode = function(){
// ...
// }
return this
}
var ca = paper.node(250, 150, 50.0, "hola");
var list = paper.nodeList();
list.push(ca);
Some examples may fall down if there is no global 'paper'
The context of Raphael.fn.yrMethod will be the instance (paper)
This example creates a raphael object which wraps a g element, which is for some reason not currently supported:
(function(R){
function g(_paper){
var _canvas = _paper.canvas,
_node = document.createElementNS("http://www.w3.org/2000/svg", "g");
_canvas.appendChild(_node);
this.add = function(rElement){
_node.appendChild(rElement.node);
}
this.remove = function(rElement){
_canvas.appendChild(rElement.node);
}
this.transform = function(tString){
_node.setAttribute('transform', tString);
}
}
R.fn.g = function(){
return new g(this);
}
})(Raphael);
this code allow you to create a node with a text (it returns a set) and you can manipulate it as a Raphael object (put the method after loading the dom):
function loadShape(){
Raphael.fn.node = function(x, y, radius, txt){
this.x = x;
this.y = y;
this.radius = radius;
this.txt = txt;
this.drawCircle = function () {
return paper.circle(this.x, this.y, radius);
};
this.drawText = function () {
return paper.text(this.x, this.y, this.txt);
};
this.draw = function(){
var group = paper.set();
var circulo = paper.circle(this.x, this.y, radius);
var texto = paper.text(this.x, this.y, this.txt);
group.push(circulo);
group.push(texto);
return group;
}
this.init = function(ox, oy, r, t){
this.x = ox;
this.y = oy;
this.radius = r;
this.txt = t;
};
// etc…
return this;
};
var paper = new Raphael(document.getElementById("wrapper"), "100%", "100%");
//var nodo = paper.node();
//nodo.init(50, 50, 2.0, "soy un nodo");
var nodo = paper.node(250, 150, 50.0, "hola");
nodo.draw();
//circ.attr({"propiedad":"hola"});
//alert(circ.attr("propiedad"));
}
Tell me if this was useful to you!
Related
I'm currently developing a small game for my capstone project. In the game, the user tries to avoid rectangles of random sizes the move from the right side of the screen to the left at a set speed.
It's built using object-oriented Javascript, and I've assigned it an anonymous function, however, I can't seem to get it to generate a shape and animate it more than the initial time the function is called. The problem can be solved if I create more than one object, but I would like this function to run automatically and generate more than just the first rectangle.
I've tried to call the function with an interval to force it to re-run the function with no results. I also attempted to separate the initialization function to call it with a parameter to generate the number of shapes given to it.
This is the function that generates the shape with the initial call, and determines the color, size, and location as well as draws it on the canvas.
var randomRectangle = function(){
this.init = function() {
this.speed = 4;
this.x = canvas.width-50;
this.y = Math.floor(Math.random()*280) + 40;
this.w = Math.floor(Math.random()*200) + 50;
this.h = Math.floor(Math.random()*150) + 20;
this.col = "#b5e61d";
}
this.move = function(){
this.x -= this.speed;
}
this.draw = function(num){
draw.rectangles(this.x, this.y, this.w, this.h, this.col);
}
};
This is where the object is initialized and the loop generates all objects and animations on the canvas.
randRecs = new randomRectangle();
randRecs.init();
function loop(){
draw.clear();
player.draw();
player.move();
wall1.draw();
wall2.draw();
randRecs.draw();
randRecs.move();
}
var handle = setInterval(loop, 30);
I expected the rectangle to continuously be generated at a new y-coordinate with a new size, then move from the right side of the screen to the left. However, only one rectangle is created and animated.
var list = [];
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var randomRectangle = function() {
this.init = function() {
this.speed = 4;
this.x = canvas.width - 50;
this.y = Math.floor(Math.random() * 280) + 40;
this.w = Math.floor(Math.random() * 200) + 50;
this.h = Math.floor(Math.random() * 150) + 20;
this.col = "#b5e61d";
}
this.move = function() {
this.x -= this.speed;
// restart x position to reuse rectangles
// you can change the y value here to a new random value
// or you can just remove with array.splice
if (this.x < -50) this.x = canvas.width - 50;
}
this.draw = function(num) {
draw.rectangles(this.x, this.y, this.w, this.h, this.col);
}
};
function loop() {
draw.clear();
//player.draw();
//player.move();
//wall1.draw();
//wall2.draw();
// call the methods draw and move for each rectangle on the list
for (var i=0; i<list.length; i++) {
rec = list[i];
rec.draw();
rec.move();
}
}
// spawn any number of new rects in a specific interval
var rectsPerSpawn = 1;
function addRects() {
for (var i=0; i<rectsPerSpawn; i++) {
if (list.length < 100) {
var rec = new randomRectangle();
list.push(rec);
rec.init();
}
}
}
// every half second will spawn a new rect
var spawn = setInterval(addRects, 500);
var draw = {
clear: function () {
ctx.clearRect(0,0,canvas.width,canvas.height);
},
rectangles: function (x, y, w, h, col) {
ctx.fillStyle = col;
ctx.fillRect(x,y,w,h);
}
}
var handle = setInterval(loop, 30);
<canvas></canvas>
What is confusing is how this simple script works fine:
function A() {
this.value = 0;
}
A.prototype.foo = function() {
console.log(this.value);
};
function B() {
this.value = 1;
this.foo();
}
B.prototype = Object.create(A.prototype);
B.prototype.bar = function() {
console.log(this instanceof A);
}
new B().bar();
// outputs 1, true
However, this larger script gives an error this.loadDimensions is not a function:
Basically, there is a Player class, which inherits from a MovingComponent class, which inherits from a VisibleComponent class. They all have methods attached to them.
const PX_SZ = 4, MAX_HEIGHT = 100, MIN_HEIGHT = 300;
var resources = {};
resources.sprites = {};
resources.sprites.player = new Image();
resources.sprites.player.src = "resources/sprites/player.png";
resources.sprites['default'] = new Image();
resources.sprites['default'].src = "resources/sprites/default.png";
resources.sprites.items = {};
resources.sprites.backgroundEntities = {};
var itemsTemp = ['default', 'coin0'];
for (var i=0; i<itemsTemp.length; i++) {
var item = itemsTemp[i];
resources.sprites.items[item] = new Image();
resources.sprites.items[item].src = "resources/sprites/items/" + item + ".png";
}
var backgroundEntitiesTemp = ['tree0'];
for (var i=0; i<backgroundEntitiesTemp.length; i++) {
var ent = backgroundEntitiesTemp[i];
resources.sprites.backgroundEntities[ent] = new Image();
resources.sprites.backgroundEntities[ent].src = "resources/sprites/background-entities/" + ent + ".png";
}
var canvas, ctx;
var player = new Player();
var keys = {};
var game = new Game(Math.floor(Math.random()*1000000));
var world = new World();
/** #class */
function Game(seed) {
this.seed = seed;
}
/** #class */
function World() {
this.gravity = 0.4;
this.chances = {
items: {
coin0: 0.005
},
backgroundEntities: {
tree0: 0.05
}
};
this.itemsFloating = [];
this.backgroundEntities = [];
// for spawning
this.exploredRightBound = 0;
this.exploredLeftBound = 0;
}
World.prototype.generate = function(left, right) {
if (left >= right) throw "left >= right in World#generate(left,right)";
for (x = left; x < right; x += PX_SZ) {
// world generation code here
// coin0
var level = getGroundHeightAt(x)
if (Math.random() <= this.chances.items.coin0) {
var item = new ItemFloating("coin0", x, level-20);
this.itemsFloating.push(item);
}
if (Math.random() <= this.chances.backgroundEntities.tree0) {
var ent = new BackgroundEntity("tree0", x, level-resources.sprites.backgroundEntities.tree0.height);
this.backgroundEntities.push(ent);
}
}
};
/**
* #class
* anything that has a sprite attached to it
*/
function VisibleComponent() {
this.sprite = resources.sprites['default'];
}
VisibleComponent.prototype.loadDimensions = function() {
console.log('load');
};
VisibleComponent.prototype.draw = function() {
ctx.drawImage(this.sprite, this.x, this.y, this.width, this.height);
};
/** #class */
function Item(name="default") {
VisibleComponent.call(this);
this.name = name || "default";
this.sprite = resources.sprites.items[name];
this.loadDimensions();
}
Item.prototype = Object.create(VisibleComponent.prototype);
/** #class */
function ItemFloating(name, x, y) {
Item.call(this, name);
this.name = name;
this.x = x;
this.y = y;
this.loadDimensions(); // (when ready of now)
}
ItemFloating.prototype = Object.create(Item.prototype);
/** #class */
function BackgroundEntity(name="default", x=0, y=0) {
VisibleComponent.call(this);
this.name = name;
this.x = x;
this.y = y;
this.width = 1;
this.height = 1;
this.sprite = resources.sprites.backgroundEntities[this.name];
this.loadDimensions();
}
BackgroundEntity.prototype = Object.create(VisibleComponent.prototype);
/** #class */
function MovingEntity(x=0, y=0) {
VisibleComponent.call(this);
this.x = x;
this.y = y;
this.width = 1;
this.height = 1;
}
MovingEntity.prototype = Object.create(VisibleComponent.prototype);
MovingEntity.prototype.collisionWith = function(ent) {
return ((this.x>=ent.x&&this.x<=ent.x+ent.width) || (ent.x>=this.x&&ent.x<=this.x+this.width))
&& ((this.y>=ent.y&&this.y<=ent.y+ent.height) || (ent.y>=this.y&&ent.y<=this.y+this.height));
};
/** #class */
function Player() {
MovingEntity.call(this);
this.inventory = {};
console.log(this instanceof VisibleComponent);
this.speed = 4;
this.jumpSpeed = 8;
this.vspeed = 0;
this.sprite = resources.sprites.player;
this.loadDimensions();
this.direction = "right";
}
Player.prototype = Object.create(MovingEntity.prototype);
Player.prototype.draw = function() {
ctx.save();
ctx.translate(this.x, this.y);
if (this.direction == "left") ctx.scale(-1, 1); // flip over y-axis
ctx.translate(-this.sprite.width, 0);
ctx.drawImage(this.sprite, 0, 0, this.width, this.height);
ctx.restore();
}
Player.prototype.move = function() {
if (keys['ArrowLeft']) {
this.x -= this.speed;
this.direction = "left";
var leftEdge = this.x-canvas.width/2-this.width/2;
if (leftEdge < world.exploredLeftBound) {
world.generate(leftEdge, world.exploredLeftBound);
world.exploredLeftBound = leftEdge;
}
}
if (keys['ArrowRight']) {
this.x += this.speed;
this.direction = "right";
var rightEdge = this.x+canvas.width/2+this.width/2;
if (rightEdge > world.exploredRightBound) {
world.generate(world.exploredRightBound, rightEdge);
world.exploredRightBound = rightEdge;
}
}
var level = getGroundHeightAt(this.x+this.width/2);
if (this.y + this.height < level) {
this.vspeed -= world.gravity;
} else if (this.y + this.height > level) {
this.y = level - this.height;
this.vspeed = 0;
}
if (keys[' '] && this.y+this.height == getGroundHeightAt(this.x+this.width/2)) this.vspeed += this.jumpSpeed;
this.y -= this.vspeed;
for (var i=0; i<world.itemsFloating.length; i++) {
var item = world.itemsFloating[i];
if (this.collisionWith(item)) {
if (this.inventory.hasOwnProperty(item.name)) this.inventory[item.name]++;
else this.inventory[item.name] = 1;
world.itemsFloating.splice(i, 1);
}
}
};
I'm fairly new to javascript inheritance, so I don't understand what I'm doing wrong. Also, since the first script worked, I figured there's something I'm just overlooking in my second script. Any help would be appreciated.
EDIT
In the beginning of the file, I declare player as a new Player(). resources contains Image instances that point to various image files. ctx and canvas are pretty self-explanatory globals.
Also, player isn't recognized as an instance of MovingEntity or VisibleComponent, even though Player's prototype is set to Object.create(MovingEntity.prototype), which has its prototype set to Object.create(VisibleComponent.prototype).
One other thing to mention is that in the definition of loadDimensions() in VisibleComponent, either the onload property of this.sprite is set to a function, or addEventListener() is called for 'load', depending on whether this.sprite has loaded (width != 0) or not.
In the beginning of the file, I declare player as a new Player().
That's the problem, you need to call the constructor after having set up your class. It currently doesn't throw an error about Player not being a function because the declaration is hoisted, but the prototype is not yet initialised with the value you expect so it indeed does not have a .loadDimensions() method yet.
I have a card class:
function Card() {
this.image = new Image();
this.x = 0;
this.y = 400;
this.initialX = 0;
this.initialY = 0;
this.scaleFactor = 4;
this.setImage = function(ii){
this.image.src = ii;
};
this.getWidth = function(){
if (this.image == null){
return 0;
}
return this.image.width / this.scaleFactor;
}
this.getHeight = function(){
if (this.image == null){
return 0;
}
return this.image.height / this.scaleFactor;
}
this.pointIsInCard = function(mx, my){
if (mx >= this.x && mx <= (this.x + this.getWidth()) && my >= this.y && my <= (this.y + this.getHeight()))
{
return true;
}
else{
return false;
}
};
};
I then have a deck class:
function Deck(x, y, w, h){
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.cards = [];
}
I need to add a method in Deck class similar to pointIsInCard instead it will be called pointIsInDeck. The logic will be same i.e to check whether the passed in point falls in the boundary of the object. So seeing this duplication of code I wanted to know what is a good design practice to avoid this duplication? One option I thought of was to extract the method out and create a function for generic object with x, y, width, height but again from OOP principles I thought this method should belong to the class/object. I appreciate any help! Thanks!
A common approach for what you're doing is to attach a Rectangle or similar instance with that functionality to both of your objects, that is:
class Rectangle {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
containsPoint(x, y) {
return x >= this.x && x =< this.width &&
y >= this.y && y =< this.height;
}
}
Then just add it to Card and Deck:
function Card() {
this.rect = new Rectangle(/* Your card shape */);
// ...
}
function Deck() {
this.rect = new Rectangle(/* Your deck shape */);
// ...
}
And you can do:
card.rect.containsPoint();
deck.rect.containsPoint();
If these are classes related to drawing, they would both inherit from something like Rectangle, which they would both inherit this behaviour from.
If they are gameplay-related, I would prefer them each referencing a Rectangle (or its subclass) that they would delegate all UI-related tasks to; then reduce this to the previous paragraph's solution.
You can use Function.prototype.call() to set this at a function call
function Card() {
this.x = 1; this.y = 2;
};
function Deck() {
this.x = 10; this.y = 20;
}
function points(x, y) {
// do stuff
console.log(x, this.x, y, this.y); // `this`: `c` or `d`
}
var c = new Card();
var d = new Deck();
points.call(c, 3, 4); // `this`: `c` within `points` call
points.call(d, 100, 200); // `this`: `d` within `points` call
Lately, on a number of js game making blogs and sites etc. I have seen a new convention for creating some kind of "instance". It looks like this:
var newCharacter = function (x, y) {
return {
x: x,
y: y,
width: 50,
height: 50,
update: function () {
//do update stuff here
}
};
};
var myCharacter = newCharacter(20, 30); //create "instance"
As opposed to the the traditional way:
var Character = function (x, y) {
this.x = x;
this.y = y;
this.width = 50;
this.height = 50;
this.update = function () {
//do update stuff here
};
};
var myCharacter = new Character(20, 30); //create intance
I was curious what the advantage of using the first way might be. Is it more efficent, semantic, or faster?
I've hit a wall trying to figure this out. I'm new to OO Javascript and trying to put together my first class/object. I'm trying to create a canvas loader and it's not working. I've narrowed down the error to the requestAnimationWindow portion inside my animate function in my clock class. I get a Object [object global] has no method 'animate' error. Here is my code.
HTML:
<div id="loader"><canvas id="showLoader" width="250" height="250"></canvas><div id="showTimer"><p id="elapsedTime">
<script>
var clockTest = new clock(document.getElementById("showLoader"), 0, 100);
clockTest.animate();
</script>
</p></div></div>
Javascript:
function clock(canvas, curPerc, endPrecent){
var showPerc = document.getElementById("elapsedTime");
this.canvas = document.getElementById("showLoader");
var context = this.canvas.getContext('2d');
var x = this.canvas.width / 2;
var y = this.canvas.height / 2;
var radius = 75;
this.curPerc = 0;
this.endPercent = 110;
var counterClockwise = false;
var circ = Math.PI * 2;
var quart = Math.PI / 2;
context.lineWidth = 10;
context.strokeStyle = '#ed3f36';
this.animate = function(current) {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.beginPath();
this.context.arc(x, y, radius, -(quart), ((circ) * current) - quart, false);
this.context.stroke();
this.curPerc++;
if(this.curPerc < this.endPercent) {
requestAnimationFrame(function () {
this.animate(curPerc / 100);
showPerc.innerHTML = this.curPerc + '%';
});
}
};
}
Any tips is appreciated. Thanks!
It is to do with the context of this in the anonymous function you pass to requestAnimationFrame, its not the this you think. Use a closure
i.e.
this.animate = function(current) {
var self = this; //<-- Create a reference to the this you want
self.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
/.. etc, etc..
if(self.curPerc < self.endPercent) {
requestAnimationFrame(function () {
self.animate(self.curPerc / 100); //<-- and use it here
showPerc.innerHTML = self.curPerc + '%'; //<-- and here
});
}
};
On a couple of other points, I would try to structure the object a bit better, you don't seem to be keeping reference to the properties correctly. The parameters you passed in , are not store on the object, and you are not storing the context correctly. Something like:
function clock(canvas, curPerc, endPrecent) {
var self = this;
// Set object properties here, i.e. from the parameters passed in
// Note also, anything that is a property (i.e. this. ) is public, can be accessed from otuside this object,
// whereas variable declared with var , are privte, can only be access within this object
self.canvas = canvas;
self.curPerc = curPerc;
self.endPercent = endPrecent;
self.context = self.canvas.getContext('2d'); //needs to be store like this, if you want to access below as this.context
self.context.lineWidth = 10;
self.context.strokeStyle = '#ed3f36';
//Private variables
var showPerc = document.getElementById("elapsedTime");
var x = self.canvas.width / 2;
var y = self.canvas.height / 2;
var radius = 75;
var counterClockwise = false;
var circ = Math.PI * 2;
var quart = Math.PI / 2;
//Methods
self.animate = function (current) {
self.context.clearRect(0, 0, self.canvas.width, self.canvas.height);
self.context.beginPath();
self.context.arc(x, y, radius, -(quart), ((circ) * current) - quart, false);
self.context.stroke();
self.curPerc++;
if (self.curPerc < self.endPercent) {
requestAnimationFrame(function () {
self.animate(curPerc / 100);
showPerc.innerHTML = self.curPerc + '%';
});
}
};
}
is starting to head in a better direction.
I ran into the same problem using three.js while calling requestAnimationFrame from inside an ES6 class method and the way I ended up solving it was by:
animate() {
requestAnimationFrame(() => this.animate());
this.render();
}