How to select DOM element with jquery - javascript

I have a function in javascript that draws images on a random canvas
I select my img source using javascript default selector,then draw part this image on a desired canvas
I want to use jquery to select my img object, but when I replace var img =document ... with var img=$("#karajan"), but the function do not draw image on canvases
Also I've tried var img=$("#karajan").text() .... $("#karajan").val() .... $("#karajan").html() but none of them did not work
function drawImage() {
var img = document.getElementById("karajan");
var arr = getRandomArray();
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
var dx = ((j == 0) ? 0 : j * 150 + j * 10);
var dy = ((i == 0) ? 0 : i * 150 + i * 10);
var k = i * 3 + j;
if (k > 7) continue;
getCanvas(arr[k] - 1).drawImage(img, j * 150, i * 150, 150, 150, 0, 0, 150, 150);
}
}
}

You can just use $("#karajan").get(0). or $("#karajan")[0].

Related

Many bouncing balls in javascript

I've been trying to get this to work for a while and I've hit a block and can't get these balls to bounce off of each other and the walls. I'm trying to make essentially a virus simulator, with different balls having different properties determining infection chances whenever they contact each other. Here's the code I'm working with:
Molecule.js:
class Molecule {
constructor(_i, _max_rad){
this.moleculeIndex = _i;
this.rad = random(min_rad, _max_rad);
this.position = createVector(random(this.rad,width-this.rad),random(this.rad, height-this.rad));
this.velocity = createVector(random(-2,5),random(-2,5));
this.bounce = false;
}
render() {
noStroke();
if (this.bounce) {
let dx = this.position.x - molecules[moleculeIndex].position.x;
let dy = this.position.y - molecules[moleculeIndex].position.y;
let dist = Math.sqrt(dx * dx + dy * dy);
let normalX = dx / dist;
let normalY = dy / dist;
let midpointX = (this.position.x.x + molecules[moleculeIndexmoleculeIndex].position.x) / 2;
let midpointY = (this.position.x.y + molecules[moleculeIndex].position.y) / 2;
let dVector = (this.velocity.x - molecules[moleculeIndex].velocity.x) * normalX;
dVector += (this.velocity.y - molecules[moleculeIndex].velocity.y) * normalY;
let dvx = dVector * normalX;
let dvy = dVector * normalY;
this.velocity.x -= dvx;
this.velocity.y -= dvy;
molecules[moleculeIndex].velocity.x += dvx;
molecules[moleculeIndex].velocity.y += dvy;
}
push();
translate(this.position.x,this.position.y)
ellipse(0,0,this.rad*2,this.rad*2);
pop();
}
step() {
this.position.add(this.velocity);
}
checkEdges(){
if(this.position.x < this.rad || this.position.x > width-this.rad){
this.velocity.x = this.velocity.x * -1;
}
if(this.position.y < this.rad || this.position.y > height-this.rad){
this.velocity.y = this.velocity.y * -1;
}
}
}
Sketch.js:
let molecules = [];
let numOfMolecules = 100;
let min_rad = 10;
let max_rad = 50;
let row = 5;
let col = 5;
let gridHeight;
let gridWidth;
let moleculeKey;
let tempArray;
let intersectCount;
let numchecks;
let displayMolecules = true;
let draw_grid = true;
let display_info = true;
function setup() {
createCanvas(window.innerWidth, window.innerHeight); //create canvas size of screen
background(150, 178, 164);
createMolecules();
}
function createMolecules() {
molecules = [];
for (let i = 0; i < numOfMolecules; i++) {
molecules.push(new Molecule(i, max_rad));
}
}
function draw() {
background(150, 178, 164);
gridWidth = window.innerWidth / col;
gridHeight = window.innerHeight / row;
splitIntoGrids();
checkIntersections();
drawGrid();
renderGrid();
resetBalls();
}
function splitIntoGrids() {
moleculeKey = [];
for (let i = 0; i < row; i++) {
moleculeKey.push([]);
for (let j = 0; j < col; j++) {
moleculeKey[i].push([]);
molecules.forEach(molecule => {
if ((molecule.position.x + molecule.rad > j * gridWidth) &&
(molecule.position.x - molecule.rad < j * gridWidth + gridWidth) &&
(molecule.position.y + molecule.rad > i * gridHeight) &&
(molecule.position.y - molecule.rad < i * gridHeight + gridHeight)) {
moleculeKey[i][j].push(molecule.moleculeIndex);
}
});
}
}
}
/* Splits into grids and counts the molecules in each grid.
* Also checks molecules when overlapping between two cells
* Stores molecules in an array, to track the location of each molecule
*/
function checkIntersections() {
intersectCount = 0;
numchecks = 0;
for (let i = 0; i < moleculeKey.length; i++) {
for (let j = 0; j < moleculeKey[i].length; j++) {
// if a cell contains more than one molecule, store the molecules into temporary array
if (moleculeKey[i][j].length > 1) {
tempArray = moleculeKey[i][j];
// loops through each molecule in the temporary array
for (let k = 0; k < tempArray.length; k++) {
for (let l = k + 1; l < tempArray.length; l++) {
// calculate distance of the molecules between each other
let distanceMolecules = p5.Vector.sub(molecules[tempArray[k]].position, molecules[tempArray[l]].position);
let vectorLength = distanceMolecules.mag();
numchecks++;
//checks if molecules are intersecting
if (vectorLength < molecules[tempArray[k]].rad + molecules[tempArray[l]].rad) {
molecules[tempArray[k]].bounce = true;
molecules[tempArray[l]].bounce = true;
intersectCount++;
}
}
}
}
}
}
}
function drawGrid() {
if (draw_grid) {
for (let i = 0; i < row; i++) {
for (let j = 0; j < col; j++) {
stroke(255);
noFill();
rect(j * gridWidth, i * gridHeight, gridWidth, gridHeight);
fill(255);
textSize(12);
text(moleculeKey[i][j].length, j * gridWidth + 10, i * gridHeight + gridHeight - 10);
}
}
}
}
function resetBalls() {
for (let i = 0; i < moleculeKey.length; i++) {
for (let j = 0; j < moleculeKey[i].length; j++) {
if (moleculeKey[i][j].length > 1) {
tempArray = moleculeKey[i][j];
//console.log(tempArray);
for (let k = 0; k < tempArray.length; k++) {
for (let l = k + 1; l < tempArray.length; l++) {
let distanceMolecules = p5.Vector.sub(molecules[tempArray[k]].position, molecules[tempArray[l]].position);
let vectorLength = distanceMolecules.mag(); //get the length of vector
//checks if molecules are not intersecting
if (!vectorLength < molecules[tempArray[k]].rad + molecules[tempArray[l]].rad) {
//change back color
molecules[tempArray[k]].bounce = false;
molecules[tempArray[l]].bounce = false;
}
}
}
}
}
}
}
function renderGrid() {
molecules.forEach(molecule => {
if (displayMolecules) {
molecule.render();
}
molecule.checkEdges();
molecule.step();
});
}
With this code I get an error 'Uncaught ReferenceError: moleculeIndex is not defined' on the first line of the if(bounce), I've tried replacing moleculeIndex with some other things but really it was just hoping. Does anyone know why I'm having this problem?
Thanks.
Try replacing the: moleculeIndex with this.moleculeIndex

Why is my outer for-loop executing more iterations than it should?

can anyone tell me why my dice have gone off the image? I was expecting the outer for loop to print a row of dice 6 times. I can't figure out what I'm doing. Thanks
var backgroundImg, itemImg;
function preload() {
backgroundImg = loadImage("background.jpg");
itemImg = loadImage("Dice.png");
}
function setup() {
createCanvas(backgroundImg.width, backgroundImg.height);
image(backgroundImg, 0, 0);
imageMode(CENTER);
}
var add = 54
var xpos = 412
var ypos = 262
function draw() {
// add your for loop below
for( j=1; j <= 6; j++){
for( i=1; i <= 9; i++){
image(itemImg, xpos + add * i , ypos)
}
ypos += 72
}
}
I found the solution. This was what I had to do:
var backgroundImg, itemImg;
function preload() {
backgroundImg = loadImage("background.jpg");
itemImg = loadImage("Dice.png");
}
function setup() {
createCanvas(backgroundImg.width, backgroundImg.height);
image(backgroundImg, 0, 0);
imageMode(CENTER);
}
var add = 54
var xpos = 412
var ypos = 190
var add2 = 72
function draw() {
// add your for loop below
for( j=1; j <= 5; j++){
for( i=1; i <= 9; i++){
image(itemImg, xpos + add * i , ypos + add2 * j)
}
//ypos += 72
}
}

Game of life bug

I'm coding Conways game of life in P5JS, but I got a wierd bug. It seems to "work" but it looks all wrong. I'm not sure if it has t do with finding the neighbors, because when I call the function manually, it works. I even copied a second neighbor-counting function of the internet in there, and it works, too.
Maybe it's a visual glitch, but I'm not sure of that either, because the code looks fine.
/// <reference path="../TSDef/p5.global-mode.d.ts" />
let gridSize = 10;
let arrCurrent = create2dArray(gridSize);
let arrNext = create2dArray(gridSize);
function setup() {
createCanvas(800, 800, WEBGL);
background(0);
stroke(0, 255, 0);
noFill();
initGame();
}
function draw() {
displayCells();
calcNextGen();
}
//Returns a 2D Array
function create2dArray(size) {
let newArray = new Array(size);
for (let i = 0; i < newArray.length; i++) {
newArray[i] = new Array(1);
}
return newArray;
}
//Fills initial array with random values
function initGame() {
for (let x = 0; x < arrCurrent.length; x++) {
for (let y = 0; y < arrCurrent.length; y++) {
arrCurrent[x][y] = Math.round((Math.random()));
}
}
}
//Calculates next generation
function calcNextGen() {
for (let x = 0; x < gridSize; x++) {
for (let y = 0; y < gridSize; y++) {
let neighbors = countNeighbors1(arrCurrent, x, y);
let state = arrCurrent[x][y];
//If cell is dead and has exactly 3 neighbors, it starts living
if (state === 0 && neighbors === 3) {
arrNext[x][y] = 1;
}
//If cell lives and has too few or too many neighbors, it dies
else if (state === 1 && (neighbors < 2 || neighbors > 3)) {
arrNext[x][y] = 0;
}
else {
arrNext[x][y] = state;
}
}
}
arrCurrent = arrNext.slice();
}
//Count neighbors
function countNeighbors(x, y) {
return arrCurrent[(x + 1) % gridSize][y] +
arrCurrent[x][(y + 1) % gridSize] +
arrCurrent[(x + gridSize - 1) % gridSize][y] +
arrCurrent[x][(y + gridSize - 1) % gridSize] +
arrCurrent[(x + 1) % gridSize][(y + 1) % gridSize] +
arrCurrent[(x + gridSize - 1) % gridSize][(y + 1) % gridSize] +
arrCurrent[(x + gridSize - 1) % gridSize][(y + gridSize - 1) % gridSize] +
arrCurrent[(x + 1) % gridSize][(y + gridSize - 1) % gridSize];
}
function countNeighbors1(grid, x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let col = (x + i + gridSize) % gridSize;
let row = (y + j + gridSize) % gridSize;
sum += grid[col][row];
}
}
sum -= grid[x][y];
return sum;
}
function displayCells() {
background(0);
translate(-300, -300, 0);
for (let x = 0; x < arrCurrent.length; x++) {
for (let y = 0; y < arrCurrent.length; y++) {
push();
translate(x * 50, y * 50, 0);
if (arrCurrent[x][y] === 1) box(50);
pop();
}
}
}
function logGrid() {
console.log(arrCurrent[0]);
console.log(arrCurrent[1]);
console.log(arrCurrent[2]);
console.log(arrCurrent[3]);
console.log(arrCurrent[4]);
console.log(arrCurrent[5]);
console.log(arrCurrent[6]);
console.log(arrCurrent[7]);
console.log(arrCurrent[8]);
console.log(arrCurrent[9]);
}
I know I'm very close, but I'm banging my head against this one since 2 hours.
Here's a little P5JS Web Editor, you can copy the code over and visually see the problem.
Any help is appreciated - thank you!
arrCurrent = arrNext.slice(); doesn't create a deep copy of the grid, it just creates a shallow copy of the first dimension.
It creates a grid, where columns of arrCurrent refers to the rows of arrNext.
You've to create a completely new grid:
arrCurrent = []
for (let x = 0; x < gridSize; x++)
arrCurrent.push(arrNext[x].slice());
let gridSize = 10;
let arrCurrent = create2dArray(gridSize);
let arrNext = create2dArray(gridSize);
function setup() {
createCanvas(800, 800, WEBGL);
background(0);
stroke(0, 255, 0);
noFill();
initGame();
frameRate(10)
}
function draw() {
displayCells();
calcNextGen();
}
//Returns a 2D Array
function create2dArray(size) {
let newArray = new Array(size);
for (let i = 0; i < newArray.length; i++) {
newArray[i] = new Array(1);
}
return newArray;
}
//Fills initial array with random values
function initGame() {
for (let x = 0; x < arrCurrent.length; x++) {
for (let y = 0; y < arrCurrent.length; y++) {
arrCurrent[x][y] = Math.round((Math.random()));
}
}
}
//Calculates next generation
// - A live cell dies if it has fewer than two live neighbors.
// - A live cell with two or three live neighbors lives on to the next generation.
// - A live cell with more than three live neighbors dies.
// - A dead cell will be brought back to live if it has exactly three live neighbors.
function calcNextGen() {
for (let x = 0; x < gridSize; x++) {
for (let y = 0; y < gridSize; y++) {
let neighbors = countNeighbors1(arrCurrent, x, y);
let state = arrCurrent[x][y];
//If cell is dead and has exactly 3 neighbors, it starts living
if (state === 0 && neighbors === 3) {
arrNext[x][y] = 1;
}
//If cell lives and has too few or too many neighbors, it dies
else if (state === 1 && (neighbors < 2 || neighbors > 3)) {
arrNext[x][y] = 0;
}
else {
arrNext[x][y] = state;
}
}
}
arrCurrent = []
for (let x = 0; x < gridSize; x++)
arrCurrent.push(arrNext[x].slice());
}
function countNeighbors1(grid, x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let col = (x + i + gridSize) % gridSize;
let row = (y + j + gridSize) % gridSize;
sum += grid[col][row];
}
}
sum -= grid[x][y];
return sum;
}
function displayCells() {
background(0);
translate(-75, -75, 0);
stroke(128);
box(50*gridSize, 50*gridSize, 50);
translate(-225, -225, 0);
stroke(0, 255, 0);
for (let x = 0; x < arrCurrent.length; x++) {
for (let y = 0; y < arrCurrent.length; y++) {
push();
translate(x * 50, y * 50, 0);
if (arrCurrent[x][y] === 1) box(50);
pop();
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

Making a canvas using p5.js

enter image description hereI got an exercise , where i have to create a rectangle-canvas using p5.js , but that canvas will consist small rects ,so i do it , but there is also 1 point in the exrecise . How can i get those small rects in 2 different colors , but 50% of those colores must be green and the other red , using matrix .
Here is the code .
var matrix = [
];
var ab = 36;
for (var y = 0; y < ab; y++) {
matrix.push([])
for (var x = 0; x < 36; x++) {
matrix[y][x] = Math.floor(Math.random() * 2)
}
}
console.log(matrix)
var side = 16;
function setup() {
createCanvas(matrix[0].length * side, matrix.length * side);
background('#acacac');
frameRate()
}
function draw() {
for (var y = 0; y < matrix.length; y++) {
for (var x = 0; x < matrix[y].length; x++) {
if (matrix[y][x] == 0) {
fill(0, 255, 0)
rect(y * side, x * side, side, side)
}
else if (matrix[y][x] == 1) {
fill("red")
rect(y * side, x * side, side, side)
}
function Shuffle (arguments) {
for(var k = 0; k < arguments.length; k++){
var i = arguments[k].length;
if ( i == 0 ) return false;
else{
while ( --i ) {
var j = Math.floor( Math.random() * ( i + 1 ) );
var tempi = arguments[k][i];
var tempj = arguments[k][j];
arguments[k][i] = tempj;
arguments[k][j] = tempi;
}
return arguments;
}
}
}
so as discussed in comments , the problem reduces to filling exactly half the matrix with one color and other half with other.
your matrix is in two dimension i will give a solution in one dimension, which should be quite easy to extend to 2-d
var count = 0;
var arr = [];
for( var i = 0 ;i < ab;i++){
arr[i] = 0;
}
while(true) {
var i = floor(random(ab));
if(arr[i] !==1) {
arr[i] = 1;
count++;
}
if(count === ab/2) break; // assume ab is even
}
there is one more way
fill half the array with 1 and half with 0 and then shuffle the array
you can very easily google algorithms for shuffling,
one pseudocode i could find
// after filling half elements with 1 and half with zero
// To shuffle an array a of n elements (indices 0..n-1):
for i from n - 1 downto 1 do
j = random integer with 0 <= j <= i
exchange a[j] and a[i]
source: https://www.geeksforgeeks.org/shuffle-a-given-array/
There it is my problem
var matrix = [
];
var ab = 36;
for (var y = 0; y < ab; y++) {
matrix.push([])
for(var x = 0 ; x<ab;x++){
matrix[y][x] = Math.floor(Math.random()*1)
}
for(var x = 0 ; x<ab/2;x++){
matrix[y][x] = 1
}
}
var count = 0;
var arr = [];
for( var i = 0 ;i < ab;i++){
arr[i] = 0;
}
while(true) {
var i = Math.floor(Random(ab));
if(arr[i] !==1) {
arr[i] = 1;
count++;
}
if(count === ab/2) break; // assume ab is even
}
console.log(arr)
var side = 16;
function setup() {
createCanvas(arr[0].length * side, arr.length * side);
background('#acacac');
frameRate()
}
function draw() {
for (var y = 0; y < arr.length; y++) {
for (var x = 0; x < arr[y].length; x++) {
if (matrix[y][x] == 0) {
fill(0, 255, 0)
rect(y * side, x * side, side, side)
}
else if (matrix[y][x] == 1) {
fill("red")
rect(y * side, x * side, side, side)
}
else if (matrix[y][x] == 2) {
fill(255, 255, 0)
rect(y * side, x * side, side, side)
}
else if (matrix[y][x] == 3) {
fill(255, 0, 0)
rect(y * side, x * side, side, side)
}
}
}
}

Canvas getImageData().data return half image

I'm trying to generate a pixelated canvas from image source - but there is a strange behavior of the getImageData() function -
on images that are higher than my canvas I keep getting only the max height data [square of max-height * max-height].
is there anything I'm missing here?
function generatePixels(){
const pixel_size = 10;
const x = 0; const y = 0;
const w = temp_ctx.canvas.width;
const h = temp_ctx.canvas.height;
let min_width = w,
min_height = h,
max_width = 0, max_height = 0;
for (var j = y; j < (y+h); j += pixel_size) {
for (var i = x; i < (x+w); i += pixel_size) {
// get current pixel image data (x,y,10,10);
var data = temp_ctx.getImageData(j, i, pixel_size, pixel_size).data;
// draw pixel on rendered canvas
rendered_ctx.fillStyle = '#' + (data[2] | (data[1] << 8) | (data[0] << 16) | (1 << 24)).toString(16).slice(1);
rendered_ctx.fillRect((j + pixel_size), (i + pixel_size), 10, 10);
}
}
}
You can find an example of the code here:
https://codepen.io/AceDesigns/pen/dZEmjZ
Please find the workable code below. The issue is with the for loop condition.
for (var j = y; j < (y+h); j += pixel_size) {
for (var i = x; i < (x+w); i += pixel_size) {

Categories

Resources