Image not able to load when using p5js outside of online editor - p5.js

I am using p5js and I am trying to load and display some images in my directory. I am trying to use the loadImage() method in my preload function to load an image. However, when I run the program, I get these errors
Fetch API cannot load file:///Users/mainuser/Documents/school/Senior/FinalProject/imgs/arms_up.png. URL scheme "file" is not supported.
🌸 p5.js says: It looks like there was a problem loading your image. Try checking if the file path (imgs/arms_up.png) is correct, hosting the file online, or running a local server. (More info at https://github.com/processing/p5.js/wiki/Local-server)
TypeError: Failed to fetch
at fetch (p5.js:28096)
at p5._main.default.loadImage (p5.js:80673)
at p5.js:62949
at preload (script.js:118)
at p5._start (p5.js:62905)
at new p5 (p5.js:63261)
at _globalInit (p5.js:62189)
My imgs folder is within the same folder as my index.html
My guess is that fetch() might need an actual URL instead of a file path.
Anybody else run into this problem? I've attached my code below (i took out irrelevant code). Thank you!
index.html
<!DOCTYPE HTML>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#1.3.1/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#teachablemachine/pose#0.8/dist/teachablemachine-pose.min.js"></script>
<script src="script.js"></script>
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.0/lib/p5.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Pose Game</h1>
<button type="button" onclick="init()">Start Game!</button>
<button type="button" onclick="restart_game()">Restart Game</button>
<div id="main-div">
<div id="flex-div">
<div id="webcam-div">
<canvas id="canvas"></canvas>
</div>
<div id="p5-div"></div>
</div>
</div>
</body>
</html>
script.js
let arms_up_png;
let left_arm_up;
let right_arm_up;
function preload() {
arms_up_png = loadImage("imgs/arms_up.png");
}
function setup() {
var canvas = createCanvas(400, 400);
canvas.parent('p5-div');
}
function draw() {
background('green');
image(arms_up_png, 50, 50, 20, 20);
}

You are correct that fetch() will not work with local file paths, and because p5js needs to load the contents of the image file in order to display it you also cannot use local file paths with the p5js loadImage() function. In order to run your sketch locally you will need to use a local web server. The Visual Studio Code Live Server extension is quite handy for this purpose.

Related

jsPDF + html2canvas in HTA/IE11

I want to generate a PDF from a hta file (http-equiv="x-ua-compatible" content="ie=11"). Append to child is working like a charme. However it doesn't work with jsPDF... Any help appreciated!
Scripts included:
<script src="polyfill.min.js"></script><!-- https://cdn.jsdelivr.net/npm/promise-polyfill#7/dist/polyfill.min.js -->
<script src="jspdf.js"></script><!-- https://github.com/MrRio/jsPDF/blob/master/src/jspdf.js -->
<script src="html2canvas.js"></script><!-- https://html2canvas.hertzen.com/dist/html2canvas.js -->
DIV to print:
<div class ="print" id="print">
<h3>print!</h3>
<input type="button" id="pdfPrint" value="PDF erstellen" />
</div>
Script Code:
document.getElementById('pdfPrint').addEventListener('click', function() {
html2canvas(document.getElementById("print")).then(function(canvas) {
// document.getElementById("print").appendChild(canvas);
var img = canvas.toDataURL("image/jpeg", 1.0);
var pdf = new jsPDF();
pdf.addImage(img,'JPEG',20,20);
pdf.save('Testung.pdf');
}
});
});
I've made a test with your code. And I've found that there will be ReferenceError: 'jsPDF' is undefined in IE11.
The key point is the reference of jsPDF. You should replace your jsPDF script with latest one:https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js
Then the running result is as the capture below:

p5 setVoice not working

while trying to change the voices in the p5.speech, setVoice function just not working at all...
I've been tried both string and index, but still went wrong, is there anyone can help? I would be really appreciated!!
Thanks!
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.5/p5.min.js">
</script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.5/addons/p5.dom.js">
</script>
<script src="p5.speech.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<button id='talks'>
click to talk
</button>
<script>
$('#talks').click(function(){
console.log('hi')
var talk= new p5.Speech()
talk.onLoad=Voices
function Voices(){
talk.listVoices()
talk.setVoice('Google UK English Male')
}
talk.speak("What's up")}
</script>
</body>
</html>
below is the output of talk.listVoices() :
enter image description here
Firstly my answer is not the full solution, but there are some simple SyntaxErrors in your example. Thats why it's not runable for me at all.
You are opening click( but didn't close it, for better clearance i reformatted your code and added the closing bracket.
A function normally get's called with brackets, so it should be Voices();
This is not necessary for every Browser, but normally an ending line in JavaScript get's an ;
$('#talks').click(
function(){
console.log('hi');
var talk= new p5.Speech();
talk.onLoad=Voices();
function Voices(){
talk.listVoices();
talk.setVoice('Google UK English Male');
}
talk.speak("What's up");
}
)
With that changes i get an console output like this:
VM43:3: hi
p5.speech.js:136 p5.Speech: voices not loaded yet!
p5.speech.js:89 p5.Speech: voices loaded!

How to put p5.js canvas in a html div

I am trying to add p5.js to the background of one section in my webpage. I am new to javascript and can't figure out how to bind the two parts together.
You need to add code in your setup.
Make sure you have the function in a script tag in the html as well.
Note you do not add # in the .parent().
var myCanvas = createCanvas(winWidth, winHeight);
myCanvas.parent("idnameofdiv");
if you are inserting multiple p5js canvas in one page and are already using the form new p5(sketch), you can just pass the id of your div as second parameter, like new p5(sketch, idnameofdiv)
Because the function sketch should be unique (if you don't use an IIFE), I like to put the id in the name of the sketch function as well
function sketch_idnameofdiv(p) {
p.setup = function () {
p.createCanvas(400,400);
}
p.draw = function () {
// stuff to draw
}
}
new p5(sketch_idnameofdiv, 'idnameofdiv')
if you don't need to insert multiple p5js canvas in one page, I guess you are looking for Michael Paccione's answer
P5.js gives you an html canvas that you can use for positioning your sketch.
Here is an example of using a canvas as the background of a div:
<!DOCTYPE html>
<html>
<head>
<style>
canvas {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index:-1;
}
</style>
</head>
<body>
<h1>Heading</h1>
<p>paragraph 1</p>
<p>paragraph 2</p>
<script src="processing-1.4.1.min.js"></script>
<div id="canvasContainer">
<canvas data-processing-sources="rectangles.pde"></canvas>
</div>
</body>
This is Processing.js instead of P5.js, but the idea is the same. Try googling something like "html canvas as background" for a ton of results. Try something out, and post an MCVE if you get stuck.
To be more detailed about the answer:
function setup() is a function which executes ojnly once at the startup.
function draw() is a function which executes after setup() and it reloads on every frame of the picture.
The code goes like this:
<!DOCTYPE html>
<html>
<head>
<title>P5.js Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
<script>
function setup() {
var canvas = createCanvas(400, 400);
canvas.parent('canvasForHTML');
}
function draw() {
background(127);
}
</script>
</head>
<body>
<h1>Canvas for visualization</h1>
<div id="canvasForHTML"></div>
<p>Move your mouse around to see circles.</p>
</body>
</html>
Check this:
https://jsfiddle.net/sugandhnikhil/74Ltdy8z/1/

Read/write to Parse Core db from Google Apps Script

I'm just starting to use Parse Core (as Google'e ScriptDB is being decommissioned soon) and am having some trouble.
So I'm able to get Parse Core db to read/write using just a standard HTML page as shown below:
<!doctype html>
<head>
<meta charset="utf-8">
<title>My Parse App</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.18.min.js"></script>
</head>
<body>
<div id="main">
<h1>You're ready to use Parse!</h1>
<p>Read the documentation and start building your JavaScript app:</p>
<ul>
<li>Parse JavaScript Guide</li>
<li>Parse JavaScript API Documentation</li>
</ul>
<div style="display:none" class="error">
Looks like there was a problem saving the test object. Make sure you've set your application ID and javascript key correctly in the call to <code>Parse.initialize</code> in this file.
</div>
<div style="display:none" class="success">
<p>We've also just created your first object using the following code:</p>
<code>
var TestObject = Parse.Object.extend("TestObject");<br/>
var testObject = new TestObject();<br/>
testObject.save({foo: "bar"});
</code>
</div>
</div>
<script type="text/javascript">
Parse.initialize("PyMFUxyBxR8IDgndjZ378CeEXH2c6WLK1wK2JHYX", "IgiMfiuy3LFjzH0ehmyf5Rkti8AmVtwcGqc6nttN");
var TestObject = Parse.Object.extend("TestObject");
var testObject = new TestObject();
testObject.save({foo: "bar"}, {
success: function(object) {
$(".success").show();
},
error: function(model, error) {
$(".error").show();
}
});
</script>
</body>
</html>
However, when I try to serve that up using the HtmlService shown below, I get no response from Parse. Parse Core.html basically has all of the code I have above ( only thing I changed was to remove the css calls).
function doGet() {
var htmlPage = HtmlService.createTemplateFromFile('Parse Core.html')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE)
.setTitle('Parse Core Test');
return htmlPage;
}
Link to ParseDb Library for Apps Script
Here is the key to add the library: MxhsVzdWH6ZQMWWeAA9tObPxhMjh3Sh48
Install that library and it allows you to use most of the same methods that were used by ScriptDb. As far as saving and querying go they almost identical. Make sure to read the Library's notes, how to add the applicationId and restApiKey. It is a little different that you can silo data by classes which must be defined in the call to Parse.
Bruce here is leading the way on database connection for Apps Script, he has plenty of documentation on using Parse.com, and also his own DbConncection Drive that would allow you to use a number of back-end systems.
Excel Liberation - Bruce's Site.

Is it possible generated from local file image from html5-canvas

My canvas has image which programly generated from local file or from images from internet. When I try to save it using toDataURl function I get secure error. How can I save result (without server, using only js ) and is it possible?
I know about security rule but maybe there is some solution to bypass this rule
All my code is in github if need
Shame! Don't bypass rules built to provide security for our users.
The key to satisfying CORS security and still getting what you need is to let the user select the image file you need to load into canvas.
If the user selects the file, CORS security is satisfied and you can use the canvas as you need (including using canvas.toDataURL to save the canvas).
Here are the steps to let a user select a file from their local drive:
Add an html input element with type="file"
The user clicks browse on this element and selects their file
When the user clicks OK, use window.URL.createObjectURL to create a URL from their selected file.
Create a new Image and set its source to the URL you created in #3.
Use context.drawImage to draw your new image on the canvas.
The resulting canvas is CORS compliant so canvas.toDataURL will work.
Here's example code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
$("#fileInput").change(function(e){
var URL = window.webkitURL || window.URL;
var url = URL.createObjectURL(e.target.files[0]);
var img = new Image();
img.onload = function() {
canvas.width=img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
ctx.fillStyle="black";
ctx.fillRect(0,canvas.height-30,canvas.width,30);
ctx.fillStyle="white";
ctx.font="18px verdana";
ctx.fillText("I'm OK with CORS!",5,canvas.height-8);
}
img.src = url;
});
$("#save").click(function(){
var html="<p>Right-click on image below and Save-Picture-As</p>";
html+="<img src='"+canvas.toDataURL()+"' alt='from canvas'/>";
var tab=window.open();
tab.document.write(html);
});
}); // end $(function(){});
</script>
</head>
<body>
<input type="file" id="fileInput">
<button id="save">Save</button><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Resources