I'm making a canvas game in JavaScript and have some trouble saving the data. I'm placing images on the canvas with a for-loop and I want to save information for each image in objects. For each image an object.
function CreateBlocks(){
for(var i = 0; i <= blocks; i++){
var img = new Image();
img.src = "/images/Block.png";
blockObject = {
x: x,
y: y,
points: 10
}
ctx.drawImage(img,x,y);
x += 100;
y += 100;
}
}
Now this obviously overwrites the blockObject everytime it loops. I tried adding to loop value to the name of the object like block[i]Object or blockObject[i] but that returns syntax errors.
I could just create a single dimension array for each value, but that seems rather messy to me. How can I create the objects in the loop?
Simply use an array and push the new object each time:
function CreateBlocks(){
var arr = [];
for(var i = 0; i <= blocks; i++){
var img = new Image();
img.src = "/images/Block.png";
arr.push({
x: x,
y: y,
points: 10
});
ctx.drawImage(img,x,y);
x += 100;
y += 100;
}
}
If you create a blockObjects array, your second idea, using the blockObject[i] syntax will work:
var blockObjects=[];
function CreateBlocks(){
for(var i = 0; i <= blocks; i++){
var img = new Image();
img.src = "/images/Block.png";
blockObjects[i] = {
x: x,
y: y,
points: 10
};
ctx.drawImage(img,x,y);
x += 100;
y += 100;
}
}
Related
I can't seem to figure out why my code doesn't work. What I'm essentially trying to do is generate a 10x10 tile based map using arrays.
The idea is to create an object called Box with an 'x' and 'y' axis property and also an image object within the box. Then, each position in the 2d array is populated with a box object.
I then want to draw all these arrays out on a canvas. Each tile(or array element) is a 64x64 box.
const ROW = 10;
const COLS = 11;
const SIZE = 64;
var canvas = document.getElementById("canvas");
var surface = canvas.getContext("2d");
//creating tile
function box() {
this.xaxis = 56;
this.yaxis = 0;
this.img = new Image();
this.img.src = "box_image.png";
}
//creating map
var map =[];
function setMap() {
for (var i = 0; i < ROW; i++) {
for (var o = 0; o < COLS; o++) {
map[i][o] = new box();
}
}
}
//rendering map
function render() {
for (var i = 0; i < map.length; i++) {
for (var x = 0; x < map.length; x++) {
var tile = map[i][x];
tile.xaxis *= i;
tile.yaxis *= x;
surface.drawImage(tile.img, tile.xaxis, tile.yaxis, 64, 64);
}
}
}
setTimeout(render, 10);
Adding a few elements you forgot, here's how I would do it.
Fiddle
HTML
<canvas id="canvas" width="1000" height="1000"></canvas>
<!-- set canvas size -->
JS
const ROW = 10;
const COLS = 11;
const SIZE = 64;
var canvas = document.getElementById("canvas");
var surface = canvas.getContext("2d");
//creating tile
function box() {
this.xaxis = 56;
this.yaxis = 0;
this.src = "https://cdn4.iconfinder.com/data/icons/video-game-adicts/1024/videogame_icons-01-128.png"; //save path to image
}
//creating map
var map =[];
function setMap() {
for (var i = 0; i < ROW; i++) {
var arr = []; //make new row
map.push(arr); //push new row
for (var o = 0; o < COLS; o++) {
map[i].push(new box()); //make and push new column element in current row
}
}
}
//rendering map
function render() {
for (var i = 0; i < ROW; i++) { //For each row
for (var x = 0; x < COLS; x++) { //And each column in it
var tile = map[i][x];
tile.xaxis *= i;
tile.yaxis += (x*SIZE); //increment y value
var img = new Image();
img.onload = (function(x,y) { //draw when image is loaded
return function() {
surface.drawImage(this, x, y, 64, 64);
}
})(tile.xaxis, tile.yaxis);
img.src = tile.src;
}
}
}
setMap(); //create the grid
render(); //render the grid
There are a number of errors in your code.
First you are loading the same image 110 times. Load it once and that will save a lot of memory and time.
You create a single dimetioned array map
map = [];
Then attempt to access to as a two dim map. map[i][o] that will not work. You need to create a new array for each row.
You create the function to populate the map setMap() but you never call the function.
The Boxes you create have the yaxis value set to 0. When you call render and multiply it by the column index the result will be zero, so you will only see one column of images. You need to set the yaxis value to some value (64)
Below is your code fixed up with some comments. I left the zero yaxis value as maybe that is what you wanted. The image is created only once and the onload event is used to call render When setMap is called I add a new array for each row. I call setMap at the bottom but can be called anytime after you declare and define var map = [];
const ROW = 10;
const COLS = 11;
const SIZE = 64;
const canvas = document.getElementById("canvas");
const surface = canvas.getContext("2d");
const image = new Image();
image.src = "box_image.png";
// onload will not fire until all the immediate code has finished running
image.onload = function(){render()}; // call render when the image has loaded
//creating tile
function Box() { // any function you call with new should start with a capital
this.xaxis = 56;
this.yaxis = 0; // should this not be something other than zero
this.img = image;
}
//creating map
const map =[];
function setMap() {
for (var i = 0; i < ROW; i++) {
var row = []; // new array for this row
map[i] = row;
for (var o = 0; o < COLS; o++) {
row[o] = new box();
}
}
}
//rendering map
function render() {
for (var i = 0; i < map.length; i++) {
for (var x = 0; x < map[i].length; x++) { // you had map.length you needed the array for row i which is map[i]
var tile = map[i][x];
tile.xaxis *= i;
tile.yaxis *= x; // Note you have zero for yaxis?? 0 times anything is zero
surface.drawImage(tile.img, tile.xaxis, tile.yaxis, 64, 64);
}
}
}
setMap(); // create the map
I am a beginer. I want to create a pixel art site. For this I try to develope my javascript code. Now I am on the way to simplify the code by setting the different rectangles using var as object and array to avoid to type milles of lines. Than I think to create at the second part an array constructor with defining coords(other x, other y) for every single rectangle in 2D array.
At the moment I don't relise why the first part of the code is not working. Can you please suggest your mind? Thanks a lot in advance.
Here is my code (link on JS Bin):
var canvas;
var ctx;
var x = 0;
var y = 0;
var w = 10; // Width=10px
var h = w; // Heigth=10px
function init() {
canvas = document.querySelector('#myCanvas');
ctx = canvas.getContext('2d');
draw();
}
// Create a rect by path method for restoring the buffer
var rect;
function draw(){
ctx.beginPath();
ctx.rect(x,y,w,h);
}
var c = ['#66757F', '#F7F7F7', '#CCD6DD']; // Setting a color palette as an array
for (var i=0; i<c.length; i++){
c[i]=ctx.fillStyle();
}
// Define colored rectangles as the Objects
var r1 = {rect;[0]}
var r2 = {rect;[1]}
var r3 = {rect;[2]}
ctx.fill();
// Setting three rectangle by diagonal
var r=[r1,r2,r3];// Array of setted rectangles
function draw(){
for (var j=0; j<r.length; j++){
r[j]=ctx.moveTo(x+w*j,y+h*j);
}
}
for (var j=0; j<r.length; i++){
r[j]=ctx.moveTo(x+w*j,y+h*j);
}
You typed 'i++' when using the letter 'j'.
Not sure whether this solves the problem.
Why do you use Math.abs in
var w = Math.abs(-10); // Width=10px
Isn't it easier to set 'var w' to 10 ?
var w = 10;
Is what you're looking for how to create classes and make objects from that class?
If so this is how you would create a class and make objects.
//This will hold all of your objects.
var listOfObjects = [];
//This is a class. You can create objects with it.
function myClass() {
//location
this.X = 0;
this.Y = 0;
//size
this.width = 5;
this.height = 5;
}
function CreateNewObject() {
//This will create and add an object of myClass to your array.
//Now you can loop through the array and modify the values as you wish.
listOfObjects.push(new myClass());
}
Using jsDraw2DX, I am trying to use a series on concentric circles to display a position upon a floor plan. An array holds all drawn circles to permit clean removal. The original plan was to have them appear one-by-one, stay for 5 seconds, then to disappear one-by-one. I backed off of that due to troubles with setTimeout, and decided that just the circles image was enough, provided it could stay for a bit, then disappear, ready for the next locate operation. In the stripped down code below, The circles draw OK and remove OK, provided the one alert (marked in the code) is present, but not otherwise.
How might I make this work in the case that no alert was present?
How might I add a 5 second delay before removal?
How might it also work with an additional slight delay between drawing or removing each circle?
CTest
var oldCircle = new Array;
var iter = 0;
var rad = 4;
document.addEventListener("click", printMousePos);
function printMousePos(e) {
var cursorX = e.clientX-10;
var cursorY = e.clientY-10;
//alert("clicked: X: " + cursorX + " Y: " + cursorY);
rad = 4;
animateLocator(cursorX, cursorY);
}
function animateLocator(x, y) {
//alert("Entered animateLocator: rad: "+rad+" x: "+x+" y: "+y);
var start = new Date().getTime();
//alert("starting push");
pushall(rad, x, y);
iter = 0;
//for(i=0; i<10; i++) {
// pushFunc(rad+i*4, x, y);
//}
alert("starting pop"); // This alert box makes it work OK; otherwiudse nothing appears.
setTimeout(popall(), 2000);
}
function pushall(rad, x, y) {
iter = 0;
for(i=0; i<10; i++) {
pushFunc(rad+i*4, x, y);
}
}
function popall() {
iter = 0;
for(i=0; i<10; i++) {
popFunc();
}
}
function pushFunc(rad, x, y) { oldCircle.push(drawCircle(rad, x, y)); }
function popFunc() { oldCircle.pop().remove(); }
function drawCircle(rad, x, y) {
iter++;
//alert("drawCircle rad: "+rad+" x: "+x+" y: "+y);
//Create jxColor object
var col = new jxColor("red");
//Create jxPen object
var pen = new jxPen(col,'2px');
//Create jsGraphics object
var gr = new jxGraphics(document.getElementById("graphics"));
var ctr = new jxPoint(x,y);
var cir = new jxCircle(ctr, rad+iter*4, pen);
//alert("after jxcircle");
cir.draw(gr);
//alert("after draw");
return cir;
}
demo
Remove the alert and Change:
setTimeout(popall(), 2000);
To:
setTimeout(popall, 2000);
I want to create a few instance of this class
var fruit = {
texture: new Image(),
speed: 5,
x: 0,
y: 0,
};
function fruits(speed, x, y)
{
fruit.speed = speed;
fruit.x = x;
fruit.y = y;
return fruit;
};
but when i create new object the all value was overridet by last created object. How can i repair this?
My loop:
var apples = [];
for(var i = 0; i < 10; i++)
{
apples[i] = new fruits(5, Math.floor((Math.random()*775)+1), 0);
apples[i].texture.src = "_img/apple.png";
}
The other answers which are appearing here are just bizarre. Here's the solution:
function fruits(speed, x, y)
{
this.texture = new Image( );
this.speed = speed;
this.x = x;
this.y = y;
};
Notice that the keyword this is used to set attributes. That means that when you call
var apple = new fruits( blah blah );
then apple will be set to a new object which has texture, speed, x and y attributes. There is no need to reference some global object to store these; they are stored in the newly created object itself.
Also I would rename it; the convention is to use singular names and a capital first letter for objects, so Fruit would make more sense (allowing new Fruit(...))
function Fruit( speed, x, y ){
var fruit = {}; // or use some base object instead of {}
fruit.texture = new Image();
fruit.speed = speed || 5;
fruit.x = x || 0;
fruit.y = y || 0;
return fruit;
};
var apples = [];
for( var i=0; i<10; i++ ){
apples[i] = Fruit( 5, Math.floor((Math.random()*775)+1), 0 );
apples[i].texture.src = "_img/apple.png";
}
Douglas Crockford - Power Constructor, 'new', 'this' and more
You got an object here:
var fruit = {
texture: new Image(),
speed: 5,
x: 0,
y: 0, // Note the superflous comma, which might break the code in some IE versions
};
And a function here:
function fruits(speed, x, y) {
fruit.speed = speed;
fruit.x = x;
fruit.y = y;
return fruit;
};
The function modifies above object whenever it is called and returns it.
Now, what you want is a constructor, but you don't have one here.
This, would be a constructor for a new Fruit:
function Fruit(speed, x, y) {
this.texture = new Image();
this.speed = speed || 5; // Note: Using logical OR to emulate default values for the argument
this.x = x || 0;
this.y = y || 0;
// Note: There is no return here!
}
var a = new Fruit(2, 1, 10);
var b = new Fruit(4, 10, 20);
a === b; // Returns false, you got two instances :)
new may have the functionality of being able to create instances of a Function, but you can still override this behavior by returning manually from within the constructor Function.
Also, even if you left out the return fruit in your original code, you would get back an empty instance of fruits since you don't assign any properties to the newly created instance.
In my Fruit example I reference the instance object via the this keyword, so I can assign speed, image, x and y to each instance created.
You might also want to read:
http://bonsaiden.github.io/JavaScript-Garden/#function.constructors
http://bonsaiden.github.io/JavaScript-Garden/#function.this
function fruits(speed, x, y) {
return {
texture: new Image(),
speed: speed,
x: x,
y: x,
}
};
Try such constructor:
function Fruit(speed, x, y) {
return {
speed: speed,
x: x,
y: y
}
}
alert(new Fruit("mySpeed", 1, 2).speed);
I am using the following code to try out the canvas element
Shape = function(x,y){
this.x = x;
this.y = y;
};
shapes = new array();
shapes.push(new Shape(50,50,10,10));
shapes.push(new Shape(100,100,10,10));
shapes.push(new Shape(150,150,10,10));
function animate(){
context.clearRect(0,0, canvas.width(),canvas.height());
var shapesLength = shapes.length;
for(var i = 0; i < shapesLength; i++){
var tmpShape = shapes[i];
tmpShape.x++;
context.fillRect(tmpShape.x,thmpShape.y,10,10);
}
context.fillStyle = 'yellow';
context.fill();
if(playAnimation){
setTimeout(animate, 1)
}
}
However, when I run this in the browser I get the following error -
ReferenceError: array is not defined
shapes = new array();
I have tried making it a global and local variable I just cant see where I am going wrong?
array should be capitalized, as that is the name of the constructor:
shapes = new Array();
In addition it's better to use the square bracket notation to create an array. Like this:
shapes = [];