Connecting the HTML input page with p5.js - javascript

I want to get the data from input tags and use them in the equation.
I have tried a lot a lot of solutions, nothing worked.
I want it to start setup after click one button, and start animate after pressing the other button.
press button1
load the data from the html
set up the canvas using those data
execute draw() for ever.
I did not find much documentation.
Here is my html:
<label class="col-lg-2" for="n4" id="m2">mass sq 2</label>
<input class=" col-lg-2" name="n4" type="number" id="m2" label="mass sq 2" />
<label class="col-lg-2" for="n5" id="r">Ratio</label>
<input class="ana col-lg-2" name="n5" type="number" id="r" label="Ratio" />
<button class="col-lg-2 btn btn-danger" style="margin-left: 10%;
height:30px;"> <h3> change </h3> </button>
and here is the p5.js code:
button1 = CreateButton('submit1');
button2 = CreateButton('submit2');
let digits = document.getElementById('m2').Value;
const timeSteps = 10 ** (digits - 1);
let m1 = document.getElementById('m1').Value;
function preload() {
blockImg = loadImage('block.png');
clack = loadSound('clack.wav');
}
function setup() {
button2.mousePressed(start);
}
function draw() {
button2.mousePressed(finish);
}
function start() {
createCanvas(windowWidth, 200);
block1 = new Block(100, 20, m1, 0, 0);
const m2 = pow(100, digits - 1);
block2 = new Block(300, 100, m2, -1 / timeSteps, 20);
countDiv = createDiv(count);
countDiv.style('font-size', '72pt');
}

This answer uses instance mode to create a canvas with width and height set from user inputs. This allows us to call createCanvas() inside of setup. The code only allows us to create one canvas but it would not be hard to modify so that multiply canvases could be created, however, we should never call createCanvas more than once for each instance of p5.
var canvas = null;
function createP5 (){
let canvasWidth = document.getElementById("widthInput").value;
let canvasHeight = document.getElementById("heightInput").value;
if (canvas === null){
canvas = new p5(function (p) {
p.setup = function (){
p.createCanvas(canvasWidth, canvasHeight);
}
p.draw = function(){
p.background(55);
p.stroke(0);
p.rect(p.width/5, p.height/5, p.width/5 * 3, p.height/5 * 3);
}
}, "canvas-div");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>
<div id="canvas-div">
</div>
<input type="button" value="create canvas" onclick='createP5()'/>
<textarea id="widthInput"></textarea>
<textarea id="heightInput"></textarea>

You're asking a few different questions:
How do I run code when a user presses a button?
There are a few ways to do this, but it sounds like you're looking for the onclick attribute. You can Google "JavaScript onclick" for a ton of resources.
How do I run a P5.js sketch from JavaScript code?
For this, you probably want to use instance mode to have more control over exactly when the sketch is created. See this page for more info.
The best advice I can give you is to start smaller. Start with a simple page that shows a single button that prints something to the console when you click it. Then add a simple P5.js sketch using instance mode. Work forward in small steps instead of trying to do everything all at once.
Good luck.

Related

JS: Function works manually in console but not executed automatically in code

I copied this code snippet from here: https://codepen.io/duketeam/pen/ALEByA
This code is supposed to load a picture and make it grayscale after clicking on the button.
I want to change the code such that the picture comes out immediately as grayscale without having to click on the button, hence why I commented it out and included makeGray() in the onload part of the <input...>. But this doesnt work. Where am I going wrong here?
I have tried to leave out the makeGray()and just upload the picture and type makeGray() in the console and it does its job perfectly fine, but I need it to execute automatically. I also tried to just put all the code from the makeGray() function in the upload() function but also here it won't trigger.
var image = null;
function upload() {
//Get input from file input
var fileinput = document.getElementById("finput");
//Make new SimpleImage from file input
image = new SimpleImage(fileinput);
//Get canvas
var canvas = document.getElementById("can");
//Draw image on canvas
image.drawTo(canvas);
}
function makeGray() {
//change all pixels of image to gray
for (var pixel of image.values()) {
var avg = (pixel.getRed() + pixel.getGreen() + pixel.getBlue()) / 3;
pixel.setRed(avg);
pixel.setGreen(avg);
pixel.setBlue(avg);
}
//display new image
var canvas = document.getElementById("can");
image.drawTo(canvas);
}
<script src="https://www.dukelearntoprogram.com/course1/common/js/image/SimpleImage.js">
</script>
<h1>Convert Image to Grayscale</h1>
<canvas id="can"></canvas>
<p>
<input type="file" multiple="false" accept="image/*" id="finput" onchange="upload();makeGray()">
</p>
<p>
<!---- <input type="button" value="Make Grayscale" onclick="makeGray()" -->
</p>
<script src="./index.js"></script>
There's something you need to wait for, but I'm not sure exactly what it is. If you wrap the function in a setTimeout, it works fine. You might want to wait for a few more milliseconds for clients with slower systems or bigger files. If you ever figure out what is taking a while to do, you can instead use .then or await just to be safe.
var image = null;
function upload() {
//Get input from file input
var fileinput = document.getElementById("finput");
//Make new SimpleImage from file input
image = new SimpleImage(fileinput);
//Get canvas
var canvas = document.getElementById("can");
setTimeout(() => {
//change all pixels of image to gray
for (var pixel of image.values()) {
var avg = (pixel.getRed() + pixel.getGreen() + pixel.getBlue()) / 3;
pixel.setRed(avg);
pixel.setGreen(avg);
pixel.setBlue(avg);
}
image.drawTo(canvas);
}, 100);
}
<script src="https://www.dukelearntoprogram.com/course1/common/js/image/SimpleImage.js">
</script>
<h1>Convert Image to Grayscale</h1>
<canvas id="can"></canvas>
<p>
<input type="file" multiple="false" accept="image/*" id="finput" onchange="upload();">
</p>
<script src="./index.js"></script>

Problem with drawing Canvas using for loop in JavaScript

I am unable to draw rectangles in canvas within for loop in JavaScript. Sometimes they are visible for a fraction of second, but they disappear instantly. No errors in developer console - tested on Firefox & Chrome, so problem isn't browser-related. Seems like only I encountered this issue within my class, despite having exactly the same (or slightly adjusted to my needs) code.
Code was tested on multiple browsers, the problem itself seems to occur only on my laptop/browser - rest of my colleagues haven't encountered this issue, apart from some typos etc.
The general idea is to receive a result similar to this one:
function Draw() {
var l = liczba.value; // user-input based loop control
var xpos = ypos = 300; // Left side rectangles starting drawing position
var xneg = 600, yneg = 300; // Right side rectangles starting drawing position
var canvas = document.getElementById('image');
var context = canvas.getContext('2d');
context.fillStyle = 'red';
for(var i = 0; i < l; i++) {
context.fillRect(xpos, ypos, 100, 100);
context.strokeRect(xpos, ypos, 100, 100);
console.log("Left Canvas Painted!"); // Debug
context.fillRect(xneg, yneg, 100, 100);
context.strokeRect(xneg, yneg, 100, 100);
console.log("Right Canvas Painted!"); // Debug
xpos += 50; xneg -= 50; ypos += 50; yneg += 50; // change next canvas' starting position by...
}
}
<body>
<form method="post" id="f" onsubmit="Draw();">
<label>Podaj liczbę figur do narysowania: </label>
<input type="text" name="liczba" id="liczba">
<input type="submit" name="send" id="send" value="Zatwierdź">
</form>
<canvas id="image" width="1200" height="800">Canvasy nie działają</canvas>
</body>
Try changing the button from a submit button to a normal button and call Draw() on a click event.
<input type="button" onclick="Draw()" name="send" id="send" value="Zatwierdź">
The answer to this issue was pretty straight-forward, thanks to #jcbbdrn - a minor oversight on my part. Due to page reload on form submitting, whole canvas was flushed down the toilet. After implementing a regular button and assigning to it an onclick event, the problem has been solved.

How do I make my submit button display the uploaded file without leaving the current pagte

my code is n not working and I am sure its because the code is not
correct.I would like to get the submit button to display a picture of a
molecule using JSmol. Any help!??
<script>
var Info = {
width: 550,
height: 550,
serverURL: "http://chemapps.stolaf.edu/jmol/jsmol/jsmol.php ",
use: "HTML5 WEBGL JAVA",
j2sPath: "jsmol/j2s",
script: "load 1BNA.pdb; set spin x 15; set spin y 15; set spin z 15; spin on;
wireframe on; spacefill off",
console: "jmolApplet0_infodiv"
}
</script>
<form>
Select a file: <input type="file" name="usr_file" required>
<input type="submit" onclick="myFunction(Info)">
</form>
<p id="upload"></p>
<script>
function myFunction() {
var x = document.getElementById("Info").required;
document.getElementById("upload").innerHTML = x;
}
</script>
I may my answer a little bit off but im using the same logic in my vuejs component.
in input change event im catching the event so i can get file(s) from it ( onFilesUpload function ).
then im creating image using FileReader ( createImage function ) then i push e.target.result to my images array. then you can set image result to <img src="image_path" />

User-uploaded image as game background

I'm trying fix this game for a friend (so I don't exactly know what all his code is doing). What I want to do is take an image uploaded by the user and set it as the background permanently even after closing app. Here's what I have right now:
The assets are loaded here:
game.stage.backgroundColor = '#000000';
game.load.image('GameFrame.png', 'assets/GameFrame.png');
game.load.image('game_frame', 'assets/GameFrame.png');
The default image "game_frame" is set here:
create: function()
{
this.frameGroup = game.add.group();
this.game_frame_background = game.add.sprite(0, 0,
'game_frame_background');
this.frameGroup.add(this.game_frame_background);
this.frameGroup.add(this.wordGroup);
this.game_frame = game.add.sprite(0, 0, 'game_frame');
this.frameGroup.add(this.game_frame);
this.frameGroup.x = GAME_WIDTH / 2 - this.game_frame.width / 2;
this.frameGroup.y = GAME_HEIGHT / 2 - this.game_frame.height / 2;
}
Lastly, I put the file input js in the HTML file:
<body>
<div id="gameDiv">
<button onclick="document.getElementById('file-input').click();">Change Background</button>
<input id="file-input" type="file" name="name" style="display: none;"/>
</div>
</body>
This is where I'm stuck. I think I need to either change the name of the user's image to "GameFrame.png" OR I need to load the user's image as an asset replacing "assets/GameFrame.png" asset. But I don't know how to do either of these things.

How to program javascript radio buttons

I have this piece of code that will eventually be a little drawing tool in which the user will be able switch between a pencil and an eraser. I am trying to program the eraser at the moment. However, if the user selects the eraser radio button and then selects the pencil radio button(deselects the eraser), the eraser does not 'turn off'.
This is all done with HTML's canvas element and the eraser takes advantage of:
context.globalCompositeOperation="destination-out";
As the code below shows, I thought I might be able to go through and reverse some of the properties depending on which button was clicked, for instance changing the globalCompositeOperation to equal 'source-over' or another property of globalCompositeOperation, however as far as I know, once a property has been set for it the only way to change it is to reset the entire canvas, which would delete everything.
Then I thought I might be able to set the opacity of the brush using:
context.globalAlpha=0;
so that when the pencil tool is selected the eraser tool still erases, but at 0% opacity, so it shouldn't do anything. Unfortunatly, none of this worked.
I'm self taught so although I know a moderate amount about the HTML canvas, I've found it difficult to learn about the JS side of programming radio buttons.
I guess my question is, if some code is activated through a radiobutton onclick event, how do I deactivate the code once the radiobutton is deselected.
Thanks to any suggestions, any help is wanted!
Here's my code:
(sorry about the formatting, stack overflow didn't like my indents)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="main">
<div class="tools" style="position:fixed;">Pencil:<input type="radio" name="toolSelect" onclick="pencilCheck();" id="pencilSelect"></div>
<div class="tools" style="position:fixed; left: 80px;">Rubber:<input type="radio" name="toolSelect" onclick="rubberCheck()" id="rubberSelect"></div>
<canvas id="canvas">This is a web application, you need to update your browser.</canvas><!-- the canvas -->
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
//Makes the canvas the size of the browser window
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context.fillStyle = "red";
context.fillRect(40,40,250,100);
function rubberCheck(){
var dragging = false;
var erase = function(rubber){
if(dragging){
context.beginPath();
context.arc(rubber.clientX, rubber.clientY, 10, 0, Math.PI*2);
context.fill();
context.globalCompositeOperation="destination-out";
context.globalAlpha=1;
}
}
var click = function(rubber){
dragging = true;
erase(rubber);
}
var unclick = function(){
dragging = false;
}
canvas.addEventListener('mousedown', click);
canvas.addEventListener('mousemove', erase);
canvas.addEventListener('mouseup', unclick);
}
if(pencilCheck){
var dragging = false;
var erase = function(rubber){
if(dragging){
context.beginPath();
context.arc(rubber.clientX, rubber.clientY, 10, 0, Math.PI*2);
context.fill();
context.globalCompositeOperation="destination-over";
context.globalAlpha=0;
}
}
var click = function(rubber){
dragging = true;
erase(rubber);
}
var unclick = function(){
dragging = false;
}
canvas.addEventListener('mousedown', click);
canvas.addEventListener('mousemove', erase);
canvas.addEventListener('mouseup', unclick);
}
</script>
</body>
You have:
> <input type="radio" name="toolSelect" onclick="pencilCheck();" id="pencilSelect">
but there is no pencilCheck function. Later there is:
> if (pencilCheck) {
The function should probably be called "setTool" or similar. Pass a reference to the button that was clicked to the function using this and add a value attribute that is the tool that the button represents:
<input type="radio" ... value="pencil" onclick="setTool(this);" ...>
Then set the value of a variable to indicate the selected tool, say selectedTool:
// Initial state is no tool selected (?)
var selectedTool = null;
function setTool(el) {
if (el.checked) selectedTool = el.value;
}
Do the same with other radio buttons so selectedTool always represents the currently checked checkbox. Note that you have a reset button, you need to add a listener so when it's clicked you reset the value of selectedTool (that can use a click listener on the button or a reset listener on the form, if you're using a form, but you don't seem to be using one).

Categories

Resources