remove button when pressed in p5.js - p5.js

How do I remove a button after pressing it in p5.js? I've tried the following code but it doesn't do anything.
var button
function setup() {
createCanvas(500, 550);
}
function draw() {
background(220);
button = createButton("Press to continue")
button.position(100,525)
button.mousePressed(function(){button.remove()})
}

You are recreating the button on every frame. If you move your button creation code to your setup function it should work.
var button
function setup() {
createCanvas(500, 550);
button = createButton("Press to continue")
button.position(100,525)
button.mousePressed(function(){button.remove()})
}
function draw() {
background(220);
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
</head>
<body>
</body>
</html>

Related

function won`t run in if statement (eventlistener && eventlistener) javascript

I'm trying to get an if statement going to get api results.
First I put eventlisteners(click) on my images and when they are BOTH clicked, the get-api-results function should run.
I know I asked something similar before but I got that one screwed up, with this I`m a little closer I think.
Here`s the code
import axios from 'axios';
const container = document.getElementById('container')
let img = document.createElement("img");
img.src = "https://picsum.photos/200/301";
let img2 = document.createElement("img2");
img2.src = "https://picsum.photos/200/300";
const imgCheck = img.addEventListener("click", function(e) {
console.log("check")
})
const img2Check = img2.addEventListener("click", function(e) {
console.log("ok")
})
img.onclick = function () {location.href = "http://localhost:1234/pageTwo.html";};
document.body.appendChild(img);
document.body.appendChild(img2);
if (imgCheck && img2Check){
async function fetchRecipeOne() {
try {
const result = await axios.get('https://api.spoonacular.com/recipes/complexSearch?query=pasta&maxFat=25&number=2&apiKey=0b4d29adff5f4b41908e8ef51329fc48', {
headers: {
"Content-Type": "application/json"
}
})
console.log(result);
} catch (e) {
console.error(e);
}}
fetchRecipeOne();
} else {
console.log('no results');
}
And the html pages
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>Title</title>
</head>
<body>
<img ><img/>
<script type="module" src="app.js"></script>
</body>
</html>
And page 2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>Title</title>
</head>
<body>
<img id="img2"><img/>
<script type="module" src="app.js"></script>
</body>
</html>
Again, I`m pretty new to this stuff so if can give me enough details to sort this out you would do me a big favour.
Thanks!
Tom
addEventListener() does not return anything.
Maybe you can create a variable and change it in the eventlistener, like so:
let imgCheck = false;
img.addEventListener("click", function(e) {
imgCheck = true;
});
let img2Check = false;
img2.addEventListener("click", function(e) {
img2Check = true;
});
Also you redirect the user when he click on img, reset the click so to say. Maybe delete that
And the where you define img2 you try to create an element with the name 'img2' which isn't a valid element.
So change:
let img2 = document.createElement("img2");
To:
let img2 = document.createElement("img");
Lastly you check is the user has clicked on both the images when the script runs, what you can do is set the if statement in the async function, and call the function when the user clicks on a img.
So it could look something like:
import axios from 'axios';
const container = document.getElementById('container')
let img = document.createElement("img");
img.src = "https://picsum.photos/200/301";
let img2 = document.createElement("img");
img2.src = "https://picsum.photos/200/300";
let imgCheck = false;
img.addEventListener("click", function(e) {
imgCheck = true;
fetchRecipeOne();
});
let img2Check = false;
img2.addEventListener("click", function(e) {
img2Check = true;
fetchRecipeOne();
});
document.body.appendChild(img);
document.body.appendChild(img2);
async function fetchRecipeOne() {
if (imgCheck && img2Check) {
try {
const result = await axios.get('https://api.spoonacular.com/recipes/complexSearch? query=pasta&maxFat=25&number=2&apiKey=0b4d29adff5f4b41908e8ef51329fc48', {
headers: {
"Content-Type": "application/json"
}
})
console.log(result);
} catch (e) {
console.error(e);
}
} else {
console.log('no results');
}
}

Browser does not render appended child node

I'm experimenting with web service to transmit new elements to document DOM.
So I'm preparing a XML on server side with necessary informations to do that job. My server side XML is as followed:
<Root>
<Command>Add
<Data><button id="PB" style="width:600px; height:100px;"/></Data>
</Command>
</Root>
This XML will be caught by following page.
You will see XML has a command id "Add", which should add the nodes below data to the page.
When code is running, the button will be created and shown properly in document DOM (see code function onMessage), but it will not be rendered.
The browser debugger tells me, the width and height of the button seems to be Null. When I edit the attributes in browser debugger, the button will be rendered after change. I get this behaviour on Chrome and IE.
I need a hint, what has to be changed to let it run.
<!DOCTYPE html>
<meta charset="utf-8" />
<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:8002/chat";
var output;
var websocket;
"use strict";
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.binaryType = "arraybuffer";
websocket.onopen = function (evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt) {
writeToScreen("CONNECTED");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
function onMessage(evt) {
var parser, xmlDoc, NodeCommand, but;
parser = new DOMParser();
xmlDoc = parser.parseFromString(evt.data, "text/xml");
NodeCommand = xmlDoc.getElementsByTagName("Command");
switch (NodeCommand[0].textContent) {
case "Add":
output.appendChild(NodeCommand[0].childNodes[1].childNodes[0]);
break;
}
}
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<html>
<head>
<title>WebSocket Test</title>
</head>
<body>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
Solved!
This can't be done in this (intuitive) way. Elements have to be created over document.

Create addListener click event for more than one shape on the Google map

Look at this code:
This creates four circles on the map in a same position and it creates addListener click event for each one too but I just can click on the last one. I want to fix it in a way that I can click on all of them to make setEditable(true) for each one.
<!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script>
var selectedShape;
function clearSelection()
{
if(selectedShape)
{
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape)
{
clearSelection();
selectedShape = shape;
shape.setEditable(true);
}
</script>
<script>
var amsterdam=new google.maps.LatLng(52.395715,4.888916);
function initialize()
{
var mapProp = {center:amsterdam, zoom:7, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var myArray = [];
var myCity;
for(var i = 0; i < 4; i++)
{
myCity = new google.maps.Circle({
center:amsterdam,
radius:20000,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4
});
myArray.push(myCity);
google.maps.event.addListener(myCity, 'click', function() {setSelection(myCity)});
myArray[i].setMap(map);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
Use this instead of myCity :
google.maps.event.addListener(myCity, 'click', function() {
setSelection(this)
});
Using setSelection(myCity) will refer to the last myCity created.

Youtube player not firing onReady and onStateChange event in IE 8 and IE 10

I've spent 3 solid days trying to resolve this issue. Very quickly, the Youtube player does not fire the onReady and onStateChange event in both IE8 and IE10. I tested it on Firefox and it works. Basically, I am developing a Windows 8 metro app that uses WebView to host the html, but it also doesnt work in WebView.
The video loads and the onYouTubeIframeAPIReady is called but that's about it. Below is the html code.
The alert message in onPlayerReady and onPlayerStateChange functions doesnt get displayed in IE8 and IE10 but is displayed in Firefox.
Please help.....
<!DOCTYPE html>
<html>
<body>
<div id="player"></div>
<script>
alert('LOADING');
alert(GetUserAgent());
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady()
{ player = new YT.Player('player', { height: '315', width: '560',
videoId: 'CreKbwMTZA8', playerVars: {'autoplay': 1},
events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } });
alert('onYouTubeIframeAPIReady');
}
function onPlayerReady(event)
{
event.target.playVideo();
alert('onPlayerReady');
}
function onPlayerStateChange(event)
{
alert('onPlayerStateChange');
if (event.data == YT.PlayerState.PLAYING) { window.external.notify('PLAYING');}
else if (event.data == YT.PlayerState.ENDED) {window.external.notify('ENDED');}
}
function setSize(width, height)
{ player.setSize(width, height);
}
function GetUserAgent()
{
return navigator.userAgent;
}
</script>
</body>
</html>

WP7 - PhoneGap FileTransfer returns Null error code

I'm trying PhoneGap/Cordova 2.1.0 in WP7 for the first time, so I'm new in this.
What I should do is capturing a picture through the camera and uploading it to a server.
This is my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<title>PhoneGap WP7</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() { }
function capturePhoto()
{
// Take picture using device camera and retrieve image
navigator.camera.getPicture(
onPhotoDataSuccess,
onFail,
{
quality: 50,
destinationType: Camera.DestinationType.DATA_URL
}
);
}
function onPhotoDataSuccess(imageData)
{
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageData.substr(imageData.lastIndexOf('/') + 1);
options.mimeType="image/jpeg";
var params = new Object();
options.params = params;
var ft = new FileTransfer();
ft.upload(imageData, "http://mysite.com/upload.php", win, fail, options);
}
function onFail(message)
{
navigator.notification.alert('Failed because: ' + message);
}
var win = function(r)
{
navigator.notification.alert(r.responseCode + " - " + r.response + " - " + r.bytesSent);
}
var fail = function(error)
{
navigator.notification.alert(eval(error));
}
</script>
</head>
<body>
<h1>PhoneGap Photo Demo</h1>
<button onclick="capturePhoto();">Capture a Photo</button>
</body>
</html>
When I try this, the upload doesn't work and I get an empty error object:
{ "code":null, "source":null, "target":null, "http_status":null }
Some notes:
I followed this trick for missing whitelist in WP7.
The php code is not written by me, I would do it in asp.net, if someone could provide a working example with an asp.net webservice would be really appreciated.
Thanks.
EDIT
I debugged FileTransfer class and I get an error in JsonHelper class:
using (MemoryStream mem = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
result = deserializer.ReadObject(mem);
}
The error is: InvalidCastException
EDIT
Try replacing
uploadOptions = JSON.JsonHelper.Deserialize<UploadOptions[]>(options)[0];
with the the following
options = JSON.JsonHelper.Deserialize<string[]>(options)[0];
uploadOptions = JSON.JsonHelper.Deserialize<UploadOptions>(options);
ORIGINAL ANSWER
The easiest way to troubleshot such issues is to add reference to Cordova library source code instead of compiled WP7CordovaClassLib.dll
cordova-2.1.0-incubating-src\cordova-2.1.0\incubator-cordova-wp7\framework\WP7CordovaClassLib.csproj
http://www.apache.org/dist/incubator/cordova/
and then add breakpoint to standalone\cordovalib\Commands\FileTransfer.cs
/// <summary>
/// sends a file to a server
/// </summary>
/// <param name="options">Upload options</param>
public void upload(string options)
{
Debug.WriteLine("options = " + options);
options = options.Replace("{}", "null");
Sounds complex, but from my experience line by line debugging is the simplest way to understand what particular goes wrong with Apache Cordova in many situations.

Resources