JS: Function is not defined - javascript

I've been trying to make somekind of a starry sky. Here's the code.
When I'm trying to load the page, the console says that createHtmlElementFromStaris not defined. I can't find out why.
Thanks for your answers in advance!
var Star = function (x, y, look, color) {
var _x = x;
var _y = y;
var _look = look;
var _color = color;
this.createHtmlElementFromStar = function () {
var st = document.createElement("span");
st.style.position = "absolute";
st.style.left = x + "px";
st.style.top = (y - 10) + "px";
return st;
};
};
var Stars = function () {
var _stars = new Array();
this.createStars = function (look, count) {
var x = Math.random() * (400 - x) + x;
var y = Math.random() * (400 - y) + y;
var look = "";
var color = "#"+((1<<24)*Math.random()|0).toString(16);
_stars.push(new Star(x, y, look, color));
};
this.showStars = function () {
for (var i = 0; i < _stars.length; i++) {
document.body.appendChild(createHtmlElementFromStar(_stars[i]));
};
};};
var stars = new Stars();
stars.createStars(1, 50, "*", 150);
stars.showStars();

Related

How to set an objects pos with a different variable than the original

I am currently making a script where I should be able to pick up some circles, and currently, I am using 3 circles of a similar name, circle1, circle2, and circle3.
For some reason it doesn't do what it's supposed to and let me pick the circles up, can someone please help me? Thanks!
Here is my code:
var NUM_CIRCLES = 3;
var RADIUS = 30;
var mouseX = 0;
var mouseY = 0;
var circle1;
var circle2;
var circle3;
var val1 = new Array();
var val2 = new Array();
var val3 = new Array();
var val = new Array();
var vaal = 0;
var changeInX = 0;
var changeInY = 0;
function start(){
drawCircles();
setTimer(dragAndDrop, 10);
}
// This function draws a number of random colored circles at random points
// on the screen based on the variable NUM_CIRCLES
function drawCircles() {
circle1 = new Circle(RADIUS);
var x1 = Randomizer.nextInt(RADIUS, getWidth() - RADIUS);
var y1 = Randomizer.nextInt(RADIUS, getHeight() - RADIUS);
circle1.setPosition(x1, y1);
circle1.setColor(Randomizer.nextColor());
add(circle1);
circle2 = new Circle(RADIUS);
var x2 = Randomizer.nextInt(RADIUS, getWidth() - RADIUS);
var y2 = Randomizer.nextInt(RADIUS, getHeight() - RADIUS);
circle2.setPosition(x2, y2);
circle2.setColor(Randomizer.nextColor());
add(circle2);
circle3 = new Circle(RADIUS);
var x3 = Randomizer.nextInt(RADIUS, getWidth() - RADIUS);
var y3 = Randomizer.nextInt(RADIUS, getHeight() - RADIUS);
circle3.setPosition(x3, y3);
circle3.setColor(Randomizer.nextColor());
add(circle3);
}
function dragAndDrop(){
mouseDragMethod(mouseDrag);
}
function getMouseXY(e){
mouseX = e.getX();
mouseY = e.getY();
}
function mouseDrag(){
val1 = [];
vaal = mouseMoveMethod(getVariableXAndY);
val1.push(vaal);
val2 = [];
val2.push(mouseMoveMethod(getVariableXAndY));
val3 = [];
val3.push(mouseMoveMethod(getVariableXAndY));
val = [];
val.push(val1, val2, val3);
var mouse = new Array(mouseX, mouseY);
for (var i = 0; i < 6; i += 2){
mouseDownMethod(getMouseXY);
if (((val[i]) + RADIUS) >= (mouse[i]) && (((val[i]) - RADIUS) <
(mouse[i])) && (((val[i + 1]) - RADIUS) < (mouse[i])) && (((val[i + 1]) +
RADIUS) > (mouse[i]))){
stopTimer(dragAndDrop);
setTimer(waitForMouseMove, 10);
}
}
}
function waitForMouseMove(){
mouseMoveMethod(mouseMoveBall);
}
function mouseMoveBall(){
var oldMouseX = mouseX;
var oldMouseY = mouseY;
mouseMoveMethod(getMouseXY);
if(oldMouseX > mouseX){
changeInX = oldMouseX - mouseX;
} else if(oldMouseX < mouseX){
changeInX = mouseX - oldMouse;
} else if(oldMouseY > mouseY){
changeInY = oldMouseY - mouseY;
} else{
if(oldMouseY < mouseY){
changeInY = mouseY - oldMouseY;
}
}
}
function getVariableXAndY(variable) {
var xAndYCords = [variable.getX(), variable.getY()];
return xAndYCords;
}
Thanks
-Lerb_games

how to make a function to print a width of an image

I want to make a function, that prints a width and height of an image
var a = 3;
var s = 2 * a;
var d = a * s;
print(d);
function cube(y) {
return y * y * y;
}
var g = cube(3);
print("g: " + g);
print("h: " + cube(99));
var img = new SimpleImage("drewRobert.png");
var imgN = img.setSize(75, 75);
print(img);
var t = new SimpleImage(25, 25);
print(t);
var img9 = new SimpleImage("drewRobert.png");
var img9N = img9.getPixel(77, 90);
print(img9N);
var img8N = img9.getGreen(0, 0);
print(img8N);
function alo(s, f, j) {
return s + f + j;
}
var sd = alo(9, 3, 1);
print(sd);
img5 = new SimpleImage("palm-and-beach.png");
//that'S one here
function printW(w) {
img5 = new SimpleImage("palm-and-beach.png");
return w = print(img5.getWidth());
}
print(printW(w));
<script src="https://www.dukelearntoprogram.com/course1/common/js/cs101/SimpleImage.js"></script>

How can I find how many units are in the canvas?

I have the code listed below. The code is on https://omegalords.ga/test.world.html. I want the item to not move beyond the canvas. How can I find how many units are in the canvas? I am aware of the other errors in the console. I specifically need the canvas's dimensions in reference to items placed on the canvas. The point of the code is to create a wolf and a deer that interact. The problem is that I need to ensure that the 2 don't leave the canvas.
<script src=../script/algebra-0.2.6.min.js></script>
<canvas id="myCanvas" style="width:100%; height:100%;">
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
console.log(document.body.style)
var findDis = function(x1,y1,x2,y2){
//Finds distance rounded to the nearest 1000th
return Math.trunc(((Math.sqrt((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2)))*1000))/1000
}
var findIntersections = function(b,a,m,r){
var Fraction = algebra.Fraction;
var Expression = algebra.Expression;
var Equation = algebra.Equation;
var coords = {
l:[],
g:[]
}
//b^2 - 2bx + x^2 - 2bm^2x + b^2m^2 - r^2
var sl = algebra.parse(Math.pow(b,2)+" - "+2*b+"x + x^2 + "+Math.pow(m,2)+"x^2 -" + 2 * b * Math.pow(m,2) + "* x + " + Math.pow(b,2) * Math.pow(m,2) + " - " + Math.pow(r,2));
var sr = algebra.parse("0")
var eq = new Equation(sl, sr);
//Solves for x rounded to the nearest 1000
coords.l.push(Math.trunc((eq.solveFor("x")[0]*1000))/1000);
coords.g.push(Math.trunc((eq.solveFor("x")[1]*1000))/1000);
//Solves for y
coords.l.push(Math.trunc((eq.solveFor("x")[0] * m + a - (b * m))*1000)/1000);
coords.g.push(Math.trunc((eq.solveFor("x")[1] * m + a - (b * m))*1000)/1000);
return JSON.stringify(coords);
}
var findSlope = function(x1,y1,x2,y2){
//Finds Slope rounded to the nearest 1000th
return Math.trunc(((y1-y2)/(x1-x2))*1000)/1000;
}
var getRandomInt = function(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
var wolves = [];
var deers = [];
var animal = function(x,y){
this.age = 0
this.strength = 0;
this.x = x;
this.y = y;
this.hp = 100;
this.size = 10;
this.hunger = 0;
}
animal.prototype.move = function(){
this.nearbyPredators = [];
this.nearbyPrey = [];
for(var j = 0;j<this.predatorTypes.length;j++){
for(var i = 0;i < this.predatorTypes[j].length;i++){
if(findDis(this.predatorTypes[j][i].x,this.predatorTypes[j][i].y,this.x,this.y) < 40){
this.nearbyPredators.push(this.predatorTypes[j][i]);
}else{
console.log(findDis(this.predatorTypes[j][i].x,this.this.predatorTypes[j][i].y,this.x,this.y))
}
}
}
//finds all nearby prey
for(var j = 0;j<this.preyTypes.length;j++){
for(var i = 0;i < this.preyTypes[j].length;i++){
if(findDis(this.preyTypes[j][i].x,this.preyTypes[j][i].y,this.x,this.y) < 40){
this.nearbyPrey.push(this.preyTypes[j][i]);
}else{
console.log(findDis(this.preyTypes[j][i].x,this.preyTypes[j][i].y,this.x,this.y))
}
}
}
if(this.nearbyPredators.length == 0){
//If there are no nearby prey, move randomly
if(this.nearbyPrey.length === 0){
var tx = this.x + getRandomInt(-8,9);
var ty = this.y + getRandomInt(-9,8);
while(!(tx > (0 + this.size)) && !(ty > (0 + this.size)) && !(tx < (canvas.length - this.size)) && !(ty < (canvas.height - this.size))){
tx = this.x + getRandomInt(-8,9);
ty = this.y + getRandomInt(-9,8);
}
this.x = tx
this.y = ty
//If there is only one nearby prey, move towards it
}else if(this.nearbyPrey.length === 1){
this.nearestPrey = this.nearbyPrey[0]
var tempDis = findDis(this.x,this.y,this.nearestPrey.x,this.nearestPrey.y);
if(tempDis < 2*this.nearestPrey.size){
this.bite(this.nearestPrey)
}else {
var slope = findSlope(this.nearestPrey.x,this.nearestPrey.y,this.x,this.y);
var coords = JSON.parse(findIntersections(this.x,this.y,slope,0.125));
var ldis = findDis(this.x,this.y,coords.l[0],coords.l[1]);
var gdis = findDis(this.x,this.y,coords.g[0],coords.g[1]);
if(ldis > gdis){
this.x = coords.l[0]
this.y = coords.l[1]
}else {
this.x = coords.g[0]
this.y = coords.g[1]
}
}
//If there is more than 1, find the nearest prey and move towards it
}else {
for(var i = 0; i < this.nearbyPrey.length; i++){
this.tempDis = getDis(this.x,this.y,this.nearbyPrey[i].x,this.nearbyPrey[i].y)
if(typeof this.nearestPrey == 'undefined'){
this.nearestPrey = {
prey:this.nearbyPrey[i],
distance:this.tempDis
}
this.tempDis = undefined
}else {
if(this.tempDis > this.nearestPrey.distance){
this.nearestPrey = {
prey:this.nearbyPrey[i],
distance:this.tempDis
}
}
}
}
var slope = findSlope(this.nearestPrey.x,this.nearestPrey.y,this.x,this.y)
var coords = JSON.parse(findIntersections(this.nearestPrey.x,this.nearestPrey.y,slope,0.25));
var ldis = findDis(this.nearestPrey.x,this.nearestPrey.y,coords.l[0],coords.l[1]);
var gdis = findDis(this.nearestPrey.x,this.nearestPrey.y,coords.g[0],coords.g[1]);
if(ldis > gdis){
this.x = coords.l[0]
this.y = coords.l[1]
}else {
this.x = coords.g[0]
this.y = coords.g[1]
}
}
}else {
}
}
var grass = function(){
}
var deer = function(x,y){
animal.call(this,x,y)
deers.push(this);
this.preyTypes = [grass];
this.predatorTypes = [wolves];
}
var wolf = function(x,y){
animal.call(this,x,y)
wolves.push(this);
this.predatorTypes = [];
this.preyTypes = [deers]
}
deer.prototype = Object.create(animal.prototype);
wolf.prototype = Object.create(animal.prototype);
wolf.prototype.bite = function(prey){
prey.hp -= this.strength;
if(prey.hp < 0){
prey.die()
}
this.hunger += 40/100
console.log(this.hunger);
console.log(prey.hp)
}
new wolf(100,100)
new deer(50,50);
var init = function(){
ctx.translate(0.5, 0.5);
ctx.lineWidth = .5
window.setInterval(draw,250);
}
var draw = function(){
ctx.clearRect(0,0,canvas.width,canvas.height)
wolves[0].move();
for(var i=0;i<wolves.length;i++){
ctx.beginPath()
ctx.arc(wolves[i].x,wolves[i].y,10,0,2*Math.PI);
ctx.stroke();
}
for(var i=0; i<deers.length;i++){
ctx.beginPath();
ctx.arc(deers[i].x,deers[i].y,10,0,2*Math.PI);
ctx.stroke();
}
}
init()
</script>
var canvasHeight = canvas.clientHeight;
var canvasWidth = canvas.clientWidth;
Please note, this will also include any padding, but by default, the canvas has no padding.
Sources:
https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight
https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth
You can get the css properties:
var canvasWidth = canvas.style.width;
var canvasHeight = canvas.style.height;

Why does algebra.js fail to solve for y

On website https://omegalords.ga/world/test.html, I have a code that calculates 1 unit towards a target. In the code the slope is 1. so the x and y of the next spot to jump to should be the same. Why does it at some point change and the 2 coordinates. I have ran the numbers, but it doesn't work properly. Could someone explain hwy?
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var findDis = function(x1,y1,x2,y2){
//Finds distance rounded to the nearest 1000th
return Math.trunc(((Math.sqrt((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2)))*1000))/1000
}
var findIntersections = function(b,a,m,r){
var Fraction = algebra.Fraction;
var Expression = algebra.Expression;
var Equation = algebra.Equation;
var coords = {
l:[],
g:[]
}
//b^2 - 2bx + x^2 - 2bm^2x + b^2m^2 - r^2
var sl = algebra.parse(Math.pow(b,2)+" - "+2*b+"x + x^2 + "+Math.pow(m,2)+"x^2 -" + 2 * b * Math.pow(m,2) + "* x + " + Math.pow(b,2) * Math.pow(m,2) + " - " + Math.pow(r,2));
var sr = algebra.parse("0")
var eq = new Equation(sl, sr);
//Solves for x rounded to the nearest 1000
coords.l.push(Math.trunc((eq.solveFor("x")[0]*1000))/1000);
coords.g.push(Math.trunc((eq.solveFor("x")[1]*1000))/1000);
//Solves for y
coords.l.push(Math.trunc((coords.l[0] * m + a - (b * m))*1000)/1000);
coords.g.push(Math.trunc((coords.g[0] * m + a - (b * m))*1000)/1000);
return JSON.stringify(coords);
}
var findSlope = function(x1,y1,x2,y2){
//Finds Slope rounded to the nearest 1000th
return Math.trunc(((y1-y2)/(x1-x2))*1000)/1000;
}
var getRandomInt = function(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
var wolves = [];
var deers = [];
var deer = function(x,y){
this.x = x;
this.y = y;
this.hp = 100;
this.size = 10;
this.hunger = 0*%;
this.preyTypes = [grass];
this.predatorTypes = [wolves];
deers.push(this);
}
var wolf = function(x,y){
this.x = x;
this.y = y;
this.hp = 100;
this.size = 10;
this.hunger = 0 * %;
wolves.push(this);
this.preyTypes = [deers]
}
wolf.prototype.move = function(){
this.nearbyPredators = [];
this.nearbyPrey = [];
//finds all nearby prey
for(var j = 0;j<this.preyTypes.length;j++){
for(var i = 0;i < this.preyTypes[j].length;i++){
if(findDis(this.preyTypes[j][i].x,this.preyTypes[j][i].y,this.x,this.y) < 40){
this.nearbyPrey.push(this.preyTypes[j][i]);
}else{
console.log(findDis(this.preyTypes[j][i].x,this.preyTypes[j][i].y,this.x,this.y))
}
}
}
//If there are no nearby prey, move randomly
if(this.nearbyPrey.length === 0){
wolf.x += getRandomInt(-8,9)
wolf.y -= getRandomInt(-9,8);
//If there is only one nearby prey, move towards it
}else if(this.nearbyPrey.length === 1){
this.nearestPrey = this.nearbyPrey[0]
var slope = findSlope(this.nearestPrey.x,this.nearestPrey.y,this.x,this.y);
console.log(slope);
var coords = JSON.parse(findIntersections(this.x,this.y,slope,1));
console.log(coords);
var ldis = findDis(this.x,this.y,coords.l[0],coords.l[1]);
var gdis = findDis(this.x,this.y,coords.g[0],coords.g[1]);
console.log(ldis,gdis)
if(ldis > gdis){
this.x = coords.l[0]
this.y = coords.l[1]
console.log(this.x,this.y)
}else {
this.x = coords.g[0]
this.y = coords.g[1]
console.log(this.x,this.y)
}
//If there is more than 1, find the nearest prey and move towards it
}else {
for(var i = 0; i < this.nearbyPrey.length; i++){
this.tempDis = getDis(this.x,this.y,this.nearbyPrey[i].x,this.nearbyPrey[i].y)
if(typeof this.nearestPrey == 'undefined'){
this.nearestPrey = {
prey:this.nearbyPrey[i],
distance:this.tempDis
}
this.tempDis = undefined
}else {
if(this.tempDis > this.nearestPrey.distance){
this.nearestPrey = {
prey:this.nearbyPrey[i],
distance:this.tempDis
}
}
}
}
var slope = findSlope(this.nearestPrey.x,this.nearestPrey.y,this.x,this.y)
var coords = JSON.parse(findIntersections(this.nearestPrey.x,this.nearestPrey.y,slope,1));
var ldis = findDis(this.nearestPrey.x,this.nearestPrey.y,coords.l[0],coords.l[1]);
var gdis = findDis(this.nearestPrey.x,this.nearestPrey.y,coords.g[0],coords.g[1]);
if(ldis > gdis){
this.x = coords.l[0]
this.y = coords.l[1]
}else {
this.x = coords.g[0]
this.y = coords.g[1]
}
}
}
wolf.prototype.bite = function(prey){
prey.hp -= this.strength;
this.hunger += 40 * %
console.log(this.hunger);
console.log(this.nearestPrey.hp)
}
new wolf(100,100)
new deer(80,80);
var init = function(){
ctx.translate(0.5, 0.5);
ctx.lineWidth = .5
window.setInterval(draw,1000);
}
var draw = function(){
ctx.clearRect(0,0,canvas.width,canvas.height)
wolves[0].move();
for(var i=0;i<wolves.length;i++){
ctx.beginPath();
ctx.arc(deers[0].x,deers[0].y,10,0,2*Math.PI);
ctx.stroke();
ctx.beginPath()
ctx.arc(wolves[i].x,wolves[i].y,10,0,2*Math.PI);
ctx.stroke();
}
}
init()
</script>

Draw text pixel by pixel on canvas

I have a canvas where I use "fillText" with a string, saying for example "stackoverflow". Then I read the imagedata of the canvas in order to pick out each pixel of that text.
I want to pick the following from the pixel: x position, y position and its color. Then I would like to loop over that array with those pixels so I can draw back the text pixel by pixel so I have full control of each pixel, and can for example animate them.
However, I dont get it as smooth as I want. Look at my attach image, and you see the difference between the top text and then the text I've plotted out using fillRect for each pixel. Any help on how to make the new text look like the "fillText" text does?
Thanks
UPDATE: Added my code
var _particles = [];
var _canvas, _ctx, _width, _height;
(function(){
init();
})();
function init(){
setupParticles(getTextCanvasData());
}
function getTextCanvasData(){
// var w = 300, h = 150, ratio = 2;
_canvas = document.getElementById("textCanvas");
// _canvas.width = w * ratio;
// _canvas.height = h * ratio;
// _canvas.style.width = w + "px";
// _canvas.style.height = h + "px";
_ctx = _canvas.getContext("2d");
_ctx.fillStyle = "rgb(0, 154, 253)";
// _ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
var str = "stackoverflow";
_ctx.font = "32px EB Garamond";
_ctx.fillText(str,0,23);
_width = _canvas.width;
_height = _canvas.height;
var data32 = new Uint32Array(_ctx.getImageData(0, 0, _width, _height).data.buffer);
var positions = [];
for(i = 0; i < data32.length; i++) {
if (data32[i] & 0xffff0000) {
positions.push({
x: (i % _width),
y: ((i / _width)|0),
});
}
}
return positions;
}
function setupParticles(positions){
var i = positions.length;
var particles = [];
while(i--){
var p = new Particle();
p.init(positions[i]);
_particles.push(p);
drawParticle(p);
}
}
function drawParticle(particle){
var x = particle.x;
var y = particle.y;
_ctx.beginPath();
_ctx.fillRect(x, y, 1, 1);
_ctx.fillStyle = 'green';
}
function Particle(){
this.init = function(pos){
this.x = pos.x;
this.y = pos.y + 30;
this.x0 = this.x;
this.y0 = this.y;
this.xDelta = 0;
this.yDelta = 0;
}
}
Here is an update to your code that reuses the alpha component of each pixel. There will still be some detail lost because we do not keep the antialiasing of the pixels (which in effect alters the actual color printed), but for this example the alpha is enough.
var _particles = [];
var _canvas, _ctx, _width, _height;
(function(){
init();
})();
function init(){
setupParticles(getTextCanvasData());
}
function getTextCanvasData(){
// var w = 300, h = 150, ratio = 2;
_canvas = document.getElementById("textCanvas");
// _canvas.width = w * ratio;
// _canvas.height = h * ratio;
// _canvas.style.width = w + "px";
// _canvas.style.height = h + "px";
_ctx = _canvas.getContext("2d");
_ctx.imageSmoothingEnabled= false;
_ctx.fillStyle = "rgb(0, 154, 253)";
// _ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
var str = "stackoverflow";
_ctx.font = "32px EB Garamond";
_ctx.fillText(str,0,23);
_width = _canvas.width;
_height = _canvas.height;
var pixels = _ctx.getImageData(0, 0, _width, _height).data;
var data32 = new Uint32Array(pixels.buffer);
var positions = [];
for(i = 0; i < data32.length; i++) {
if (data32[i] & 0xffff0000) {
positions.push({
x: (i % _width),
y: ((i / _width)|0),
a: pixels[i*4 + 3] / 255
});
}
}
return positions;
}
function setupParticles(positions){
var i = positions.length;
var particles = [];
while(i--){
var p = new Particle();
p.init(positions[i]);
_particles.push(p);
drawParticle(p);
}
}
function drawParticle(particle){
var x = particle.x;
var y = particle.y;
_ctx.beginPath();
_ctx.fillStyle = `rgba(0,128,0,${particle.alpha})`;
_ctx.fillRect(x, y, 1, 1);
}
function Particle(){
this.init = function(pos){
this.x = pos.x;
this.y = pos.y + 30;
this.x0 = this.x;
this.y0 = this.y;
this.xDelta = 0;
this.yDelta = 0;
this.alpha = pos.a;
}
}
<canvas id="textCanvas"></canvas>

Categories