I'm working with Javascript, and when I type something like "Math.", I don't get any suggestions, like "PI" or "random()".
I tried installing a plugging called Aptana but it didn't solve my problem.
The same problem happens when I try to initialize an object by a constructor function:
function Box(x, y) {
this.x = x;
this.y = y;
}
var box = new Box(1, 2);
box. // nothing happens, even when I force it with CTRL + SPACE
Related
I'm a beginner on here, so apologies in advance for naivety. I've made a simple image on Brackets using Javascript, trying to generate circles with random x and y values, and random colours. There are no issues showing when I open the browser console in Developer Tools, and when I save and refresh, it works. But I was expecting the refresh to happen on a loop through the draw function. Any clues as to where I've gone wrong?
Thanks so much
var r_x
var r_y
var r_width
var r_height
var x
var y
var z
function setup()
{
r_x = random()*500;
r_y = random()*500;
r_width = random()*200;
r_height = r_width;
x = random(1,255);
y= random(1,255);
z= random(1,255);
createCanvas(512,512);
background(255);
}
function draw()
{
ellipse(r_x, r_y, r_width, r_height);
fill(x, y, z);
}
Brackets.io is just your text editor (or IDE if you want to be technical) - so we can remove that from the equation. The next thing that baffles me is that something has to explicitly call your draw() method as well as the setup() method -
I'm thinking that you're working in some sort of library created to simplify working with the Canvas API because in the setup() method you're calling createCanvas(xcord,ycord) and that doesn't exist on it's own. If you want to rabbit hole on that task check out this medium article, it walks you thru all the requirements for creating a canvas element and then drawing on that canvas
Your also confirming that you're drawing at least 1 circle on browser refresh so i think all you need to focus on is 1)initiating your code on load and 2)a loop, and we'll just accept there is magic running in the background that will handle everything else.
At the bottom of the file you're working in add this:
// when the page loads call drawCircles(),
// i changed the name to be more descriptive and i'm passing in the number of circles i want to draw,
// the Boolean pertains to event bubbling
window.addEventListener("load", drawCircles(73), false);
In your drawCircles() method you're going to need to add the loop:
// im using a basic for loop that requires 3 things:
// initialization, condition, evaluation
// also adding a parameter that will let you determine how many circles you want to draw
function drawCircles(numCircles) {
for (let i = 0; i < numCircles; i++) {
ellipse(r_x, r_y, r_width, r_height);
fill(x, y, z);
}
}
here's a link to a codepen that i was tinkering with a while back that does a lot of the same things you are
I hope that helps - good luck on your new learning venture, it's well worth the climb!
Thank you so much for your help! What you say makes sense - I basically deleted the equivalent amount of code from a little training exercise downloaded through coursera, thinking that I could then essentially use it as an empty sandpit to play in. But there's clearly far more going on under the hood!
Thanks again!
i have some doubts about Set and clone on Three js, im trying to render a scene where a sphere moves trought x axis and the camera follow the move with the lookAt, i tryed to do by myself the example on the book learning three js, but i didnt used the clone and my scene did the same but i couldnt see the sphere, with the clone i could see the sphere can someone explain me why that happen??
here is the 2 different codes:
sphere.position.copy(new THREE.Vector3(x,10,0));
sphere.position.set(new THREE.Vector3(x,10,0));
the first shows the sphere the second not :S
To elaborate on what Derte said already - set basically works like
function set(_x,_y,_z){
this.x = _x;
this.y = _y;
this.z = _z;
}
whereas copy works like:
function copy(v3){
this.x = v3.x;
this.y = v3.y;
this.z = v3.z;
}
you're passing innapropriate parameters to the set function, so it is throwing an error internally in all likelyhood. hit ctrl+shift+i in chrome to check the console, and you'll probably see that after it executes the first line fine with copy, it's throwing an error when you try to do set with (THREE.Vector3) as arguments instead of (float,float,float)
position is THREE.Vector3
look at reference
and implementation
Vector3.set takes 3 values : numbers x,y and z
Vector3.copy takes Vector3
I have created a Chrome extension that can draw the graph of the math equation user has inputted. To get the value of y easily, I used eval() (Yes I know it is bad) because the easiest way to achieve it.
var equ = $("#equ1").val(); //some element
//let's say equ = "2(2^x) + 3x"
//some magic code
//equ becomes "2*(pow(2,x))+3*x"
for(var x = -10; x < 10; x++){
var y = eval(equ.replace(/x/ig, x)); //calculate y value
drawPoint(x, y);
}
console.log("Graphing done.");
However, because of the new manifest version 2, I can't use eval anymore. I can't think of any way to manipulate the string. Any idea?
The clean way: You could try parsing the expression using Jison and building an AST from the input string. Then, associate functions with the AST node that apply the operations that the nodes represent to data given to them. This would mean that you have to explicitly put every math expression that you want to support in your grammar and your node code, but on the other hand, this would also make it easier to support mathematical operators that JS doesn't support. If you're willing to invest some time, this probably is the way to go.
The dirty way: If your extension is used on normal websites, you might be able to do some kind of indirect eval by injecting a <script> element into the website or so – however, that would likely be insecure.
Did you try New Function() ... ??
var some_logic = "2*(Math.pow(2,x))+3*x";
args = ['x', 'return (' + some_logic + ');'];
myFunc = Function.apply(null, args);
for (var x = -10; x < 10; x++) {
var y = myFunc(x);
console.log(x, y);
}
console.log("Graphing done.");
Fiddle - http://jsfiddle.net/atif089/sVPAH/
I am trying to insert this JavaScript code (that is borrowed from someone else with credit given appropriately) into an HTML page. I understand how to use the simple document.write() to display text with JavaScript and am also pretty fluent in Java but am having a hard time trying to get these functions to work properly. For lack of a better word or words I am trying to get some animation to happen using JavaScript. I found various tutorials that show some JavaScript logic and print to the screen but none of them use animation and if they do show some animation they do not show how to include it into HTML. I want to display the animation properly within the HTML page. I have been reading through the w3 schools tutorials on JavaScript and most of them either return something or use the document.write to pull information from a form or a browser. I believe this might have something to do with creating an object to use for displaying the movement in the algorithm or with the DOM for JavaScript.
The idea behind my JavaScript is, I would like to simulate a working example of the bresenham line algorithm. There is an example of this here: Bresenham line algorithm
I also saw plenty of tutorials for including the JavaScript in a secondary file and referencing the JavaScript using the src tag but I would like to keep the JavaScript at the end of the html page please.
I am also using Dreamweaver for the development of the HTML & JavaScript page.
The code is listed below. Also please feel free to list a website or tutorial I can reference to view more information on this.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bresenham's Line Algorithm</title>
</head>
<body>
<script type="text/javascript">
/**
* Bresenham's line algorithm function
* by Matt Hackett [scriptnode.com]
* #param {Object} el The element to target (accepts both strings for id's and element *objects themselves)
* #param {Number} x1 The starting X coordinate
* #param {Number} y1 The starting Y coordinate
* #param {Number} x2 The finishing X coordinate
* #param {Number} y2 The finishing Y coordinate
* #param {Object} params Additional parameters [delay, onComplete, speed]
*/
var bresenham = function(el, x1, y1, x2, y2, params) {
var
interval,
b,
m,
sx,
y;
var init = function() {
var dx, dy, sy;
// Default parameters
params = params || {};
params.delay = params.delay || 10;
params.onComplete = params.onComplete || function(){};
params.speed = params.speed || 5;
// No point in doing anything if we're not actually moving
if ((x1 == x2) && (y1 == y2)) {
plot(x1, y);
params.onComplete();
return;
}
el = ((typeof el === 'string') ? document.getElementById(el) : el);
// Initalize the math
dx = x2 - x1;
sx = (dx < 0) ? -1 : 1;
dy = y2 - y1;
sy = (dy < 0) ? -1 : 1;
m = dy / dx;
b = y1 - (m * x1);
interval = setInterval(next, params.delay);
};
/**
* Execute the algorithm and move the element
*/
var next = function() {
y = Math.round((m * x1) + b);
plot(x1, y);
x1 += (sx * params.speed);
if (x1 >= x2) {
clearInterval(interval);
params.onComplete();
}
};
/**
* Move the target element to the given coordinates
* #param float x The horizontal coordinate
* #param float y The vertical coordinate
*/
var plot = function(x, y) {
el.style.left = x + 'px';
el.style.top = y + 'px';
};
init();
};
</script>
</body>
</html>
For me the code is fine. Maybe you just need elements to move in your page. According to the documentation of the function you need to specify the id of an element present in your page.
If you intend to run it at the startup of your page you will need to wait that the DOM of your page is constructed before doing any operation on the DOM. Else your function might try to access elements that are not yet constructed.
(There are several javascript frameworks that allows it cross browser)
Declare in the body the elements you want to be affected by your algorithm.
<div id="elt1" style="position:absolute; top : 200px; left : 200px">element1</div>
Then in chrome using the console I typed this and I got the animation working. I guess you shall declare the style of your element position:absolute because your algorithm uses top and left CSS properties that work with absolute positioned elements.
bresenham("elt1",100,100,300,300,null);
You've asked a very open question, so I'm at a loss how to answer it. I assume your page had some HTML on it that you've cut out to save space, but I think we probably need to see it (or at least some of it).
In general I can suggest that you avoid the w3 school website like the plague. Go here: http://w3fools.com for an explanation of why, and then scroll down to their What Can Be Done section for some good alternative references for JavaScript, HTML and CSS.
Avoid document.write() - especially don't try to use it to update your page after it has loaded, something I assume you'll need to do a lot if you're coding an animation, but in general you won't need document.write() at all. Google yourself a tutorial on document.getElementById() - a function that returns a reference to an HTML element on your page; you can use the returned reference to change that element's text, styles (and hence location), etc.
Don't worry about including the JavaScript in a separate file at this stage. There are good reasons for doing so in a real-world website, but if you are just experimenting and learning it's probably easier to keep everything in one page.
Take a look at http://htmldog.com/ and http://www.w3schools.com/ for basic introductions of how html, css and javascript interact. Also check out www.getfirebug.com for an intro to debugging JavaScript. Once you have this base understanding it becomes a lot easier to debug your programs and search for answers to questions you have.
A brief scan of the code shows that you are calling to an HTML element el via getElementById('el'); Unless you are writing the output directly to the document as you suggested using document.write() or alert() you have to have html to display the output of your code.
From a broader view what you want is first an understanding of how javascript and html interact, then you can start googling for tutorials to complete specific elements of whatever you are trying to build ie "how to display output using innerHTML()"...
Your problem is that although you loaded in the utilities to do something, you don't have any code that utilizes it.
For example:
function hello() {
alert('Hi!');
}
The code above should tell the user "hi", right?
Wrong.
The code to tell the user "hi" is there, but I never told it to, so it wouldn't.
Your page isn't doing anything because you need to give it instructions.
From looking through the code on that page, and the source for the animator, I can tell you this:
You need to add a call to brensenham and you need to give it details of what to do.
The details it needs are:
The element to animate
The beginning position
The finishing position
So what you need to add to the end of that script tag is:
// We need to make sure the elements are ready.
window.addEventListener('load', function () {
// Get the element and set up some details.
var element = document.getElementById('whatever-its-id-is'),
beginningX = 0,
beginningY = 0,
endX = 100,
endY = 100;
// Move the element.
brensenham(element, beginningX, beginningY, endX, endY);
});
Then change beginningX, beginningY, endX, and endY to whatever you actually want them to be.
I can tell that you're brand new to this whole thing, so I hope that was simple enough.
I'm taking some information from some variables I have already defined outside this function to create a html svg text box.
Here is the function which is causing me trouble:
RenderTextBox:function()
{
alert('this.x: ' + this.x);
alert('this.y: ' + this.y);
this.textBox = paper.text(this.x, this.y, this.htmlTextBox);
}
The alerts works prefectly, and prompt me with the values expected. However, the final line which is supposed to create the text box puts them nowhere to be seen. Does anybody know why?
If I replace 'this.x, this.y..' with numerical values in the final line of the function, the text box is placed correctly. It's only when I use the 'this.x' and 'this.y' that I have issues.
Sometimes numerical values are converted in strings. That's one of the very bad point about javascript : variables are not needed to be typed.
You should try to parse them as int in order to make them react as integers again : http://www.w3schools.com/jsref/jsref_parseInt.asp
Wild Guess: an you try putting this.x and this.y into variables and then passing these variables to the function call in the last line?
Something like:
var tx = this.x;
var ty = this.y;
this.textBox = paper.text(tx, ty, this.htmlTextBox);