var ball = {
x: 20,
y: 500,
vx: 100,
vy: 100,
width: 13,
height: 13,
draw: function() {
var img = new Image();
img.src = 'images/ball.png';
img.onload = function(){
ctx.drawImage(img, this.x, this.y);
};
},
I want the drawImage() line of code to refer to the ball.x and ball.y. Instead of using ball.x and ball.y, I want to use "this" keyword so that i can turn the ball object into a function that is a mass constructor/prototype if i end up wanting to (able to make ball1, ball2, ball3 etc.). I think "this" is not referring to ball anymore because it's in a nested function? Is there any way around that without hard-coding ball.x and ball.y into the drawImage arguments?
This is one of the tricky things about JavaScript: this is dynamic. To put it simply, the solution is to put the this you want in a variable while you have it and use that variable to refer to it:
var ball = {
// ...
draw: function() {
// ...
var myself = this;
image.onload = function() {
// use myself rather than this
};
}
};
Another solution is to fix the value of this. That is done using bind:
var ball = {
// ...
draw: function() {
// ...
image.onload = function() {
// ...
}.bind(this);
}
};
That will bind the value of this inside the onload function to whatever it was when draw was called. This latter solution won't work on older browsers, but it is easily shimmed.
Yes, basically you need to use a closure. All you need to do is refer to the variables by their parent instead of by the use of this, which will actually refer to the img element in the function. So just change your code to
ctx.drawImage(img, ball.x, ball.y);
or even
ctx.drawImage(this, ball.x, ball.y);
var ball = function(){
this.x= 20;
this.y=500;
this.vx= 100;
this.vy= 100;
this.width= 13;
this.height= 13;
}
ball.prototype = {
draw: function() {
var img = new Image();
img.src = 'images/ball.png';
var balref = this;
img.onload = function(){
ctx.drawImage(img, balref .x, balref.y);
}
}
var myball = new ball();
myball.draw();
Note: not tested
Related
I just started a new project in p5, I've already used it directly imported in the browser, but this time, since it's a more complex project, I'm going to use it in webpack.
I imported the library and bootstraped it in this way:
import * as p5 from 'p5';
function setup() {
createCanvas(640, 480);
}
function draw() {
if (mouseIsPressed) {
fill(0);
} else {
fill(255);
}
ellipse(mouseX, mouseY, 80, 80);
}
But it doesn't work.
The reason is simple: webpack wraps the module in a local scope, and p5 isn't aware of it.
For this reason, I assigned the functions to the global scope:
import * as p5 from 'p5';
window.setup = function () {
createCanvas(640, 480);
}
window.draw = function () {
if (mouseIsPressed) {
fill(0);
} else {
fill(255);
}
ellipse(mouseX, mouseY, 80, 80);
}
And it works fine, but still looks wrong. I don't think that pollulating the global scope is the correct way of working with JS in 2019. Expecially if I'm using webpack and I'm about to implement TypeScript.
So, how can I tell p5 to look for the functions in the module scope and not in the global one?
You'd use instance mode, which doesn't rely on globals. Here's the example from that page:
var sketch = function( p ) {
var x = 100;
var y = 100;
p.setup = function() {
p.createCanvas(700, 410);
};
p.draw = function() {
p.background(0);
p.fill(255);
p.rect(x,y,50,50);
};
};
var myp5 = new p5(sketch);
Live Example:
var sketch = function( p ) {
var x = 100;
var y = 100;
p.setup = function() {
p.createCanvas(700, 410);
};
p.draw = function() {
p.background(0);
p.fill(255);
p.rect(x,y,50,50);
};
};
var myp5 = new p5(sketch);
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>
I am working with Processing.js (version 1.4.8).
I have 5 white points, which coordinates I chose specifically. The black dot marks the center of the sketch! I want to be able to translate and scale my sketch. ALSO, I want it to occupy the whole window.
var mapWidth, mapHeight, canvas, pjs, centerX, centerY;
var points = [[100, 100], [300, 100], [100, 300], [300, 300], [200, 200]];
var setSize = function() {
mapWidth = $(window).outerWidth();
mapHeight = $(window).outerHeight();
if (pjs) {
pjs.size(mapWidth, mapHeight);
}
};
var clear = function() {
pjs.background(200);
};
var drawPoint = function(coordinates) {
var radius = 30;
pjs.ellipse(coordinates[0], coordinates[1], radius, radius);
};
var drawPoints = function() {
pjs.fill(255);
points.map(function(point) {
drawPoint(point);
});
};
var calculateCenter = function() {
centerX = Math.floor(mapWidth / 2);
centerY = Math.floor(mapHeight / 2);
};
var drawCenter = function() {
calculateCenter();
var radius = 10;
pjs.fill(0);
pjs.ellipse(centerX, centerY, radius, radius);
console.log("center", centerX, centerY);
};
var move = function() {
pjs.translate(200, 300);
redraw();
};
var zoomIn = function() {
pjs.scale(2, 2);
redraw();
};
var draw = function() {
clear();
drawPoints();
drawCenter();
};
var redraw = function() {
clear();
draw();
};
var addEvent = function(object, type, callback) {
if (object == null || typeof object == "undefined") return;
if (object.addEventListener) {
object.addEventListener(type, callback, false);
} else if (object.attachEvent) {
object.attachEvent("on" + type, callback);
} else {
object["on" + type] = callback;
}
};
$(function() {
canvas = document.getElementById("map");
setSize();
var pjsRun = function(processingjs) {
pjs = processingjs;
pjs.setup = function() {
pjs.size(mapWidth, mapHeight);
draw();
};
};
var p = new Processing(canvas, pjsRun);
addEvent(window, "resize", function(event) {
setSize();
redraw();
});
});
Until here, everything is fine, as you can see in this CodePen.
I want to be able to resize the window AND keep the transformations (translations, scales, ...) that I had already performed.
Please, open the CodePen and try to reproduce this weird behaviour:
1) Perform one (or two) transformation(s) using the top-right buttons
The map is translated by 200 to the right and 300 downwards.
Everything OK by now...
But the problem arises now.
2) Resize the window
The five points are again where they were before the "translate" operation.
So... Again... Is there a way to resize without losing all the transformations that had been performed?
Thanks
Like you've discovered, it appears as though calling the size() function resets the transformation matrix. The short answer to your question is that you need to keep track of the transformations, and then apply them whenever you draw something.
The longer answer to your question is that you're using Processing.js a little bit differently than people typically use it. You've left out the draw() function (note that your draw() function is not the draw() function that's automatically called 60 times per second) and are trying to code event handlers yourself. This disconnect is why you're having issues.
If I were you, I'd start with a more basic sketch that starts out using Processing's built-in draw() function. Write code that draws the scene every frame. Make sure you set the translation and scale every frame. Here's an example:
var draw = function() {
scale(scaleX, scaleY);
translate(translateX, translateY);
background(200);
fill(255);
points.map(function(point) {
ellipse(coordinates[0], coordinates[1], 30, 30);
});
fill(0);
ellipse(width/2, height/2, 10, 10);
};
Then setup event listeners that change the values of scaleX and scaleY as well as translateX and translateY. Let Processing handle the rest.
cancelAnimationFrame() does not seem to work when called inside an object's method. I have tried binding the this value to the callback function (as demonstrated on MDN with setTimeout) but I received a TypeError when using cancelAnimationFrame(). I then tried setting the this value to a local variable called _this and called cancelAnimationFrame() again. That time, I did not receive an error but the animation itself is still playing. How do I cancel the animation?
I have recreated the issue I am having below. If you open a console window, you will see that the animation is still running.
function WhyWontItCancel() {
this.canvas = document.createElement("canvas");
this.canvas.width = 200;
this.canvas.height = 10;
document.body.appendChild(this.canvas);
this.draw = this.canvas.getContext("2d");
this.draw.fillStyle = "#f00";
this.position = 0;
};
WhyWontItCancel.prototype.play = function() {
if (this.position <= 190) {
this.draw.clearRect(0, 0, 400, 10);
this.draw.fillRect(this.position, 0, 10, 10);
this.position += 2;
} else {
//window.cancelAnimationFrame(this.animation.bind(this));
var _this = this;
window.cancelAnimationFrame(_this.animation);
console.log("still running");
}
this.animation = window.requestAnimationFrame(this.play.bind(this));
};
var animation = new WhyWontItCancel();
animation.play();
Seems that you miss two things here. First, this.animation = window.requestAnimationFrame(this.play.bind(this)); line is invoked always when play() is called. Contrary to what you might think, cancelAnimationFrame only removes the previously requested RAF call. Strictly speaking, it's not even necessary here. Second, you don't have to bind on each RAF call; you might do it just once:
function AnimatedCanvas() {
this.canvas = document.createElement("canvas");
this.canvas.width = 200;
this.canvas.height = 10;
document.body.appendChild(this.canvas);
this.draw = this.canvas.getContext("2d");
this.draw.fillStyle = "#f00";
this.position = 0;
this.play = this.play.bind(this); // takes `play` from prototype object
};
AnimatedCanvas.prototype.play = function() {
if (this.position <= 190) {
this.draw.clearRect(0, 0, 400, 10);
this.draw.fillRect(this.position, 0, 10, 10);
this.position += 2;
this.animationId = window.requestAnimationFrame(this.play);
}
};
You might want to add cancel into your prototype to be able to stop your animation, for example:
AnimatedCanvas.prototype.cancel = function() {
if (this.animationId) {
window.cancelAnimationFrame(this.animationId);
}
};
... but the point is, it's not useful in the use case described in the question.
I am writing some basic code using the prototypal pattern. I am trying to draw an image to canvas but it is not working. I have debugged the code within Chrome and it is because the image.onload is not firing. I don't believe the image is being loaded.
Here are the two functions that control this.
var SimpleGame = function () {
self = this; //Reference to this function
//Canvas
this.canvas = document.createElement("canvas");
this.ctx = this.canvas.getContext("2d");
this.canvas.width = 251;
this.canvas.height = 217;
//Default objects
this.bgReady = false;
this.bgImage = new Image();
};
var simpleProto = SimpleGame.prototype; //Cache the prototype
//Draw the objects on the canvas
simpleProto.draw = function() {
//Draw/ Render the canvas
document.body.appendChild(self.canvas);
//Draw the background
self.bgImage.onload = function() {
self.bgReady = true;
};
self.bgImage.src = "images/background.png";
if(self.bgReady) {
self.ctx.drawImage(self.bgImage, 10, 10);
};
}
Any idea why?
Your if(self.bgReady) is being tested before the image has a chance to load.
So naturally it will be false and drawImage will not be executed.
Fix:
Put self.ctx.drawImage in self.bgImage.onload
Good luck with your project!
I'm experimenting with the canvas element, but for some reason it doesn't display my image.
I use the following code:
function Canvas() {
this.field = function() {
var battlefield = document.getElementById('battlefield');
var canvas = battlefield.getElementsByTagName('canvas')[0];
return canvas.getContext('2d');
}
}
function Draw(canvas) {
if (!canvas) {
alert('There is no canvas available (yet)!');
return false;
}
this.canvas = canvas;
this.grass = function(pos_x, pos_y) {
var terrain = new Terrain();
var specs = terrain.grass();
var img = new Image();
img.onload = function(){
canvas.drawImage(img, specs.position_x, specs.position_y, specs.dimension_x, specs.dimension_y, pos_x, pos_y, specs.dimension_x, specs.dimension_y);
console.log('success???'); // this is being output
};
img.src = '/img/terrain.png';
}
}
(function() {
var canvas = new Canvas();
var draw = new Draw(canvas.field());
draw.grass();
})();
There are no errors, but the image just doesn't display. I've verified if the image exists and it does. I also verified the specs and they do contain what they should:
dimension_x: 25
dimension_y: 25
position_x: 0
position_y: 0
Any idea what I'm doing wrong?
http://jsfiddle.net/uwkfD/3/
pos_x and pos_y are undefined in your code. It works if you pass values for them to draw.grass():
draw.grass(0, 0);
DEMO
Tested in Chrome and Firefox.
This may be because you need a context to draw on.
Try:
this.context = canvas.getContext('2d')
Then call your draw functions on the context object not the canvas object:
this.context.drawImage(img, specs.position_x, specs.position_y, specs.dimension_x, specs.dimension_y, pos_x, pos_y, specs.dimension_x, specs.dimension_y);
It also appears that your reference to canvas is wrong too, it should be this.canvas (or this.context) not just canvas, at least as I understand scope in javascript.