Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am creating a game using JavaScript and the canvas API. I would like to implement a score at the top of the canvas which is constructed from a set of sprites on a sprite sheet. I have a sprite sheet containing images of numbers from 0 - 9. I want to know how I would go about displaying the player's current score to the canvas from the set of images. This would be including digits beyond 9(which I think confuses me most). Could you please annotate every line of code here just so I can fully understand.Thank you to everyone who replies.
Here is a quick simple solution using object property names to lookup the image details for each character you want to draw.
Convert the score to a string and then find the character code for each character in the string. Use the character code to look up the image details and then draw the image.
var numbers = { // for each character create a property that has its ASCII code
c48:{
image:imgForZero, // the image for the character zero
offx:0, // x offset if needed
offy:0, // y offset if needed
widthToNext: 10, // distance to the next character so you can have
// variable spacing
},
c49: ... // do the same for each character you want to display
// you can find the codes here
// http://www.w3schools.com/html/html_charset.asp
},
c50: ...
.. and so on
}
var chars = score.toString(); // turn score to a string
var x = 10,y = 20; // the top left of the score position
for(var i = 0; i < chars.length; i++){ // for each character
var charCode = chars.charCodeAt(i); // get the character code
var charData = numbers["c"+charCode]; // get the image details
if(charData !== undefined){ // make sure it is in the data
// draw the image with the offset
ctx.drawImage(charData.image, x + charData.offx, y + charData.offy);
// move to the next character position
x += charData.widthToNext; //
}
}
// All done
I answers to try and stop this getting a negative rating as it is a good question and shows how to use bracket notation to do lookups rather than array.find
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I'm trying to map the maximal amount of days without rain using the TRMM dataset in Google Earth Engine. I'm doing this by iterating over the collection and if no rain has fallen, one gets added to the cell (code below). When rain has fallen the value gets multiplied by 0 so the "counter" is reset. Then I would like to store each result of each iteration in a Image collection and then select the maximum value to get the longest consecutive dry period.
But that is the theory. When I put this in a script I get an error while adding the image of one iteration to a list. Does anyone know why this is and how this can be solved?
Code:
var list = [];
function drylength(current, previous){
var mask = current.remap([0], [1], 0,"precipitation").rename('precipitation');
var sum = mask.add(previous).multiply(mask);
list.push(sum);
return sum;
}
var dataset = TRMM
.filterDate("2015-01-01","2015-02-01")
.sort('system:time_start:');
var totalPrecipitation = dataset.iterate(drylength, dataset.max()
.remap([0], [0], 0, "precipitation")
.rename('precipitation'));
print(list);
print(totalPrecipitation);
Map.addLayer(ee.Image(totalPrecipitation), imageVisParam);
Furthermore it appears only 3 items are stored in the list which makes me assume the iteration is more complex than a literal iteration where all images are calculated one by one? Here is an image of the error:
Errors written if image is not visible or for search engines:
Failed to decode JSON.
Error: Field 'value' of object '{"type":"ArgumentRef","value":null}' is missing or null.
Object: {"type":"ArgumentRef","value":null}.
and:
Unknown variable references: [_MAPPING_VAR_0_0, _MAPPING_VAR_0_1].
Something like this to use a multi-value result:
function drylength(current, previous) {
previous = ee.Dictionary(previous)
var mask = current.remap([0], [1], 0,"precipitation").rename('precipitation');
var sum = mask.add(previous.get('sum')).multiply(mask);
var list = previous.get('list')
list = list.push(sum);
return ee.Dictionary({sum: sum, list: list})
}
...
var totalPrecipitation = dataset.iterate(drylength, {sum: max, list: ee.List([])})
The iterate() function runs on the server, but the list you're attempting to push into is a client-side list; that can't work. If you make it an ee.List, you might be able to get it to work, but you'll have to put it into the previous result (use previous as a dictionary to hold both).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am making a small game with basic physics and I can't figure out how to make circles interact with each other, and with rectangles. All I want is to make a solid object in the game. I can't use a engine or library, any ideas?
Have you see the tutorials on MSDN? In particular, the Detecting collisions in a 2D HTML5 game seems relevant to your interests.
In particular, here's the code used to detect collisions in that tutorial:
var circlesOverlap = function(circleA, circleB) { // Public. Returns true if the SVG circles A and B overlap, false otherwise.
var deltaX = circleA.cx.baseVal.value - circleB.cx.baseVal.value;
var deltaY = circleA.cy.baseVal.value - circleB.cy.baseVal.value;
var distance = Math.sqrt( (deltaX*deltaX) + (deltaY*deltaY) ); // The classic distance-between-two-points formula.
var radiusA = circleA.r.baseVal.value; // The radius of circle A.
var radiusB = circleB.r.baseVal.value; // The radius of circle B.
if (circleA.id == circleB.id) // If true, circleA and circleB are the same circle.
return false;
return distance <= (radiusA + radiusB);
}; // circlesOverlap()
that.circlesOverlap = circlesOverlap;
Note that the technique used in the tutorial is basically:
Track each object
Calculate the distance between the objects
Respond accordingly (e.g. when the distance is zero).
(Update: added the sample that seems most relevant to your question, per the comments below)
Do take time to read the full tutorial, though, for the full context and to ensure that due credit is duly credited.
Hope this helps...
-- Lance
Use an object to save each circle's x and y coordinates, x and y velocity (in pixels), as well as radius. keep a list of all of your circles. On each iteration of your animation loop, check that each circle's x and y coordinates plus or minus the radius are not on top of one another if the circles advance the number of pixels noted by their x and y velocities. If they are, handle what you want them to do (i.e. change direction, stop, etc.) and then redraw.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How to create SVG / canvas sketches with comic style / hand jitter using Javascript
I am aware of the xkcd style JS plotter and of this article.
Note that I am not asking for plots, but for any kind of sketching, lines, shapes, text and so on.
What further methods / technologies exist using JS?
EDIT: After having thought and read some time about this I decided to implement my own JS library providing cartoon style drawing for SVG and HTML5 canvas.
It is called comic.js and can be found here.
I would be using a Canvas library to do that, just for the sake of simplicity when it comes to manipulating shapes.
The ones I would look for are Paper.js and Fabric.js.
However, I will focus on Paper.js because it is the one I worked with.
You can draw beziers or lines to create the shapes. You can even
import SVG's if you want. You can even have predefined shapes
such as Circles/Squares etc.
So you have the shapes, now what?
You can flatten them(subdivide them into segments, adding more
vertices to their geometry). You can increase the subdivision
interval which would result in high number of vertices/nodes per
path. Subdivision interval is the parameter maxDistance of the
flatten function.
Then you can walk along the vertices of each path/shape and move each
one by a certain degree(e.g 1-2 pixels to a random direction), by using position.x and position.y
If this is what you mean:
, then here is the code :
//STEP 1 -- create shapes, a circle and rectangle in this example
var myCircle = new Path.Circle(new Point(100, 70), 50);
myCircle.strokeColor = 'white';
myCircle.strokeWidth = 2;
var mySquare = new Rectangle(new Point(350, 250), new Point(190, 100));
var square = new Path.Rectangle(mySquare);
square.strokeColor = 'white';
square.strokeWidth = 2;
//STEP 2 -- Subdivide the shapes into segments. Parameter here is the max distance we walk along-the-path before adding a new vertex
myCircle.flatten(5);
square.flatten(4);
//STEP 3 -- Loop through the segment points of the path and move each to a random value between 1 and 4
for (var i = 0; i < myCircle.segments.length; i++) { //loop for circle
myCircle.segments[i].point.x += getRandomInt(1,3);
myCircle.segments[i].point.y += getRandomInt(1,3);
};
for (var i = 0; i < square.segments.length; i++){ //loop for square
square.segments[i].point.x += getRandomInt(1,3);
square.segments[i].point.y += getRandomInt(1,3);
};
//draw the paper view
view.draw();
//Utility function that returns a random integer within a range
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
and this is the jsFiddle for it:
The issue with this scenario is that each 'point' on your canvas is an object and the high number of points/nodes/vertices is a bit heavy for the browser to handle. So this might be an obstacle if your designs are complex and/or you want to have the user interact with your drawings(the interaction might prove sluggish).
Alternatively you can use plain-old canvas to do this, without any libraries but I wouldn't do that since I smell the need for algorithms to draw the shapes manually, then introduce jitter in those algorithms. This would be much faster, in terms of computation time, but it would be harder to implement since Canvas is a low-level kind of thing - it only remembers pixels drawed on and you would need to roll-your-own data structures to remember the shapes, their positions etc etc..
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am writing a program that determines if a number is between two values in an array.
Here is an example of the array I am using.
var attackArray = new Array (2);
attackArray[0] = new Array("0","1","2","2","2","3","4");
attackArray[1] = new Array("2","3","2","3","2","3","4");
I am using the following code to compare the number against the first two values in the array. I then loop through the array until I find a line that meets the requirements. The number must be >= to the first number and <= the second number.
Here is the code that I am using.
function leveltest ( number)
{
var attack = attackArray.length;
for ( var count = 0 ; count < attack; count ++)
{
if ((number >= Number(attackArray [count][0])) && (number <= Number(attackArray [count][1])))
{
do something ;
}
}
}
If someone can look at my code and explain what I am doing wrong.
I believe you are trying to compare a number to each range of numbers defined by the item values with the same index in element 0 and element 1 of attackArray. If that is right, then the following applies.
The problems present in your code snippet were:
You have the index wrong on line 3. Your third line, attackArray[2] = new Array("1","3","2","3","2","3","4"); is creating a new third element in the attackArray created on the first line. Instead, I think you are wanting to populate the second element of attackArray which should be attackArray[1] = new Array("1","3","2","3","2","3","4"); Or you could use different array syntax as shown below.
In the function, you were using the length of attackArray var attack = attackArray.length;, to control the for loop following. Instead, you will want, var attack = attackArray[0].length; so long as attackArray[0] and attackArray[1] are the same length. You can think of it like this, you were getting your length along the wrong dimension of your array. You were getting the length "down" your array or list of objects, ran than "across" the horizontal dim of your array.
In the function, you are confused on how to loop through the array, and you have this attackArray [count][0] and attackArray [count][1] backwards. Instead they should be attackArray[0][count] and attackArray[1][count]. This will allow you to properly compare your number with each item in element 0 and the item of the same index in element 1.
The following code should be a concise, correct working piece of code to accomplish your goal. You can take and plug this in to jsfiddle.net and it should work in Chrome with the Javascript console used to view the results in the log. Here it is:
var attackArray = [];
attackArray[0] = ["0","0","2","2","2","3","4"];
attackArray[1] = ["1","3","2","3","2","3","4"];
function leveltest (number){
var attack = attackArray[0].length;
for (var count = 0;count < attack;count ++){
if ((number >= Number(attackArray [0][count])) &&
(number <= Number(attackArray [1][count]))) {
console.log(number + " matches at index " + count);
}
}
}
leveltest(2);
Looks like your second element in attackArray has the wrong index.
attackArray[2] = new Array("1","3","2","3","2","3","4");
attackArray.length == 2
you "count" can go up to 1, attackArray[1] is not defined by you.
The second comparation inside the if is wrong. At the second loop it will be attackArray[1][1] and you created an attackArray[0] and attackArray[2].
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
SOLVED
From a previous post I did and with the help of some suggestions I have managed to write a function that technically should be doing what I required it to. However the results are not entirely correct.
I have tried to add markup to the JS to explain what is going on, but to explain I have div's like follows:
<div class="section-link">
<div class="price"> £59.99</div>
</div>
<div class="section-link">
<div class="price"> £259.99</div>
</div>
I am trying to have the function hide all these div's and only show the ones if the price is within the given price range.
The data I am passing into the function is: £0.01 - £59.99 or £60.00 - £159.99 or £160.00 - £500.00
from using alert's everything is working fine, however when it gets to the if statement for the filter it is not filtering how it should be.
Any help appreciated
The js:
function price(string){ // passing in the strings as £0.01 - £59.99 and £60.00 - £159.99 etc
$('.section-link').hide(); // hide all section-link div's'
var range = string.replace(/\u00A3/g, ''); // strip pound sign's from range
var rangearray = range.split("-"); // split into 2 value arrays
lowarray = rangearray[0].toString(); // get low value as string
higharray = rangearray[1].toString(); // get high value as string
lowvalue = lowarray.replace(/ /g,''); // strip spaces
highvalue = higharray.replace(/ /g,''); // strip spaces
alert(lowvalue); // testing low value string (is alerting right) - 0.01
alert(highvalue); // testing high value string (is alerting right) - 59.99
$(".price").filter(function(){ //do a filter for all div's with the class of price
var divprice = $(this).text().replace(/\u00A3/g, ''); // strip pound sign from price value
var maindivprice = divprice.replace(/ /g,''); // strip spaces from price value
if (maindivprice >= lowvalue && maindivprice <= highvalue) {
alert(maindivprice); // alerting to see what prices it is saying are between the range (these are showing all the prices and not only ones between the range)
$(this).parent().show(); // show this parents div
} // filter to see if this price is in the price range
});
}
Is it possibly something to do with the decimal points?
Try using parseFloat on your number variable, if this was a string then it is trying to compare a string value to a float value
lowvalue = parseFloat(lowarray.replace(/ /g,'')); // strip spaces
highvalue = parseFloat(higharray.replace(/ /g,'')); // strip spaces
var maindivprice = parseFloat(divprice.replace(/ /g,'')); // strip spaces from price value