Code not working properly, image should be appearing but is not - javascript

Hey all so currently im following a tutorial, and messing around in an attempt to make a game like agar.io. Below I have included the code. So what should be happing is when I start a local host, a black canvas should appear with a white blob/circle in the middle, but whenever I run this code im only getting a black canvas. If its any help at all, im using p5 and atom together. I cant seem to figure out why its not working. In the post I have separated the code since they are separate. But they run together. Im not getting an errors. Any insight would be greatly appreciated.
function Blob() {
this.pos = createVector(width/2, height/2);
this.r = 64;
this.show = function() {
fill(255);
ellipse(this.pos.x, this.pos.y, this.r*2, this.r*2);
}
}
var blob;
function setup() {
createCanvas(600, 600);
blob = new Blob();
}
function draw() {
background(0);
blob.show();
}

Related

Using Processing's loadImage in JavaScript

I am using the Processing API to draw an image to my HTML canvas, which I can use later in the code. The JavaScript code that I have is:
var sketchProc = function(processingInstance) {
with (processingInstance) {
/* #pjs preload="images/hot-air.png" */
size(innerWidth, innerHeight);
var testImage = loadImage("images/hot-air.png");
draw = function() {
image(testImage, 0, 0, 500, 500);
}
}
}
var canvas = document.getElementById("canvas");
var processingInstance = new Processing(canvas, sketchProc);
The console says that the image has dimensions 0x0. I tried loading with Processing's directives, but I am still getting an image dimensions of 0x0. However, when I call loadImage() inside the draw loop, the program recognizes the image's dimensions of 512x512.
I do not want to continuously call loadImage() inside the draw loop. What should I do to make sure that the image loads properly outside the draw loop?
You can find a minimal working example here.
First off, thanks for posting an MCVE for us to play with.
I believe the problem is that, for some reason, the preload directive, and maybe the loadImage() function itself, doesn't work when you're writing JavaScript-only Processing.js code. I've tested this in various editors and versions of Processing.js.
So it appears that to use the loadImage() function, you should use pure Processing code. Here is a CodePen that shows how you'd do that:
<script type="application/processing">
/* #pjs preload="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg"; */
PImage testImage;
void setup(){
size(500, 500);
testImage = loadImage("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg");
println(testImage.height);
}
void draw() {
background(100);
image(testImage, 0, 0, 250, 250);
}
</script>
<canvas> </canvas>
Just for comparison, here is the same code using JavaScript-only syntax. This doesn't work.
But taking a step back: if you're comfortable using JavaScript, then why are you using Processing.js? Processing.js is designed for Processing (Java) developers who want to write Java syntax that's automagically converted to JavaScript. At this point Processing.js is pretty old and no longer maintained.
Instead, I'd recommend using P5.js. P5.js allows you to write JavaScript syntax to create web-first Processing sketches. P5.js is much newer and is still being actively developed.
Here is the same code in P5.js:
var testImage;
function preload(){
testImage = loadImage("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg");
}
function setup() {
createCanvas(400, 400);
}
function draw() {
background(100);
image(testImage, 0, 0, 250, 250);
}
Shameless self-promotion: I wrote a tutorial on the differences between Processing, Processing.js, and P5.js available here.

p5.speech.js continuous won't become true

I've been playing around with p5.speech.js the past few days. I am able to record myself for short periods of time but it stops short. I later learned that there is a continuous bool that allows you to keep recording so I decided to implement it. I set it to true with the "let continuous = true". When I ran the code the p5.speechRec still said false within the console. When I tested the console.log at the bottom it the output was true as well so I'm a little confused as to if this is a bug, a problem with chrome, or just an error that I am missing. Thanks for your help.
var myRec = new p5.SpeechRec(); // new P5.SpeechRec object
function setup()
{
// graphics stuff:
createCanvas(800, 400);
background(255, 255, 255);
fill(0, 0, 0, 255);
// instructions:
textSize(32);
textAlign(CENTER);
text("say something", width/2, height/2);
let continuous = true;
let interimResults = false;
myRec.start(continuous, interimResults);
console.log(myRec);
function speechRec(){
if (speechRec.resultValue){
createP(speechRec.resultString);
}
}
console.log("cont bool: " + continuous);
}
Questions like these are best answered by looking at the documentation for the library in question. Start by looking at the P5.js libraries page, which leads to the p5.speech documentation page here.
That documentation page says that continuous is a property of the p5.SpeechRec object, and it even links to some example code here.
Basically, you can't just pass in a random value to the start() function and expect it to work. You have to set the continuous variable yourself:
var myRec = new p5.SpeechRec('en-US', parseResult); // new P5.SpeechRec object
myRec.continuous = true; // do continuous recognition
myRec.start(); // start engine
Also, I'm not sure what your speechRec() function inside your setup() function is meant to do since you never call it, but that's not directly related to your question.

p5js positioning canvas Uncaught Type Error

I'm not sure what I'm doing wrong in this problem. I'm using OpenProcessing and trying to put a canvas element within a container but I'm running into an Uncaught TypeError, Cannot read property "id"
I'm copying the same code from https://github.com/processing/p5.js/wiki/Positioning-your-canvas
function setup() {
var cnv = createCanvas(100, 100);
var x = (windowWidth - width) / 2;
var y = (windowHeight - height) / 2;
cnv.position(x, y);
background(255, 0, 200);
}
This is my code...
function setup() {
var cnv = createCanvas(500, 100);
cnv.id("hello");
cnv.position(0,0);
}
function draw() {
}
Here is a link to my sketch...
https://www.openprocessing.org/sketch/407956
It has something to do with OpenProcessing because your code works absolutely fine on p5 editor (and locally).
The createCanvas method returns an object so calling the id function on it should not return "Cannot read property 'id' of undefined" as it did on OpenProcessing so createCanvas possibly isn't returning anything, and it should return an object according to p5 documentation..
You can try positioning the canvas using css as described in p5 wiki by adding a stylesheet that uses flexible box layout or try not using OpenProcessing if possible.
The createCanvas() function is not returning anything. This doesn't jive with what's in the P5.js reference, so I understand your confusion.
My guess is that OpenProcessing uses a slightly modified version of P5.js, because it doesn't really require any positioning. The canvas is always centered in the screen.
If you're going to continue using OpenProcessing, then I'd stop worrying about positioning the canvas yourself. Or I'd search for existing sketches that reposition the canvas and see how they do it.
Even if the createCanvas() function returns soemthing, I'm not sure what the id() function is supposed to do in this case. Nothing in the link you posted uses that function. Nonetheless, it seems to work fine if I run it locally.

JavaScript Failed to execute 'drawImage'

Ok so I'm creating a game with JavaScript Canvas Elements and such. I've been able to load in TONS of Images, but on a select few, JavaScript replies with Errors such as
Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': No function was found that matched the signature provided.
Which makes NO SENSE at all, because the same code works in other places!?!
Here is an example I have in my code:
board.drawImage(document.getElementById("player_explode"), this.x, this.y);
Inside of an objects method, Player.die(), respectively.
Does anyone know why this behaviour is coming about? I'm getting very frustrated about it...
Here is a JSFiddle to demonstrate, alonside all the code.
Player.die() is located on line[242].
The problem was the way that I was loading my Images, I should've been doing:
var image = new Image();
image.src = "imagesource.jpg";
But instead I was get the elements by id from the document page.
Resources:
Explanation on loading images
Explanation on how html loads images
you should wait all elements load,so do like this:
window.onload=function(){
board.drawImage(document.getElementById("player_explode"), this.x, this.y);
}
For people in 2021 learning React, you have to call the context.drawImage() in the img.onload or nothing will be shown on the canvas! Here is a real world working example:
useEffect(() => {
canvasRef.current.width = mapXYWH.w * UNIT
canvasRef.current.height = mapXYWH.h * UNIT
const context = canvasRef.current.getContext("2d")
map.map(o => {
const img = new Image(o.width*UNIT,o.height*UNIT)
img.src = o.normal
img.onload = () =>
context.drawImage(img, (o.x-mapXYWH.x)*UNIT, (o.y-mapXYWH.y)*UNIT)
})
}, [map, mapXYWH])
See also: React -- Canvas Won't Draw Image

canvas in canvas not displayed when requirejs structure used

I have a problem that is driving me insane.
I have something that works perfectly fine in one javascript file, but completely fails when using it with requirejs.
(function(){
define([], function (){
var Sprite = function(){
return {
spritesheet: null,
canvas: null,
context: null,
init: function(src, ctx){
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
this.context.drawImage(src, 0, 0, 10, 20, 0, 0, 10, 20);
ctx.drawImage(this.canvas, 100, 100);
}
};
};
return Sprite;
});
}
)();
And in other file I have:
(function(){
define(["r", "sprite", "player"], function (Ra, Sprite, Player){
var Game = function()
{
return {
...SOME STUFF HERE...
canvas: null,
context: null,
something: function() {
this.canvas = document.getElementById("game");
this.canvas.width = 500;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
var sprite = new Sprite();
sprite.init("image.gif", this.context);
};
};
return Game;
});
}
)();
I tried to compact the code as much as I can, I hope I didn't cut out anything important, but that is basically the part that is not working. I am also fairy new to requirejs so if I am doing something incredibly wrong, please tell me.
No matter what I do, everything seems to be fine, both canvases are created, all have the right properties, but the second one I am putting on the first one is not displayed. If I put plain image instead of canvas it works just fine, but canvas on canvas does not.
This drives me nuts, I tried so many possibilities, the code works just fine without all the requirejs stuff, but fails when I structure it that way. Does it have something to do with global scopes? How to make this work? I need canvas inside canvas.
Thank you for your time!
EDIT:
I have only <script data-main="main" src="libs/require/require.js"></script> loaded in my html file and <canvas id="game"></canvas> in body.
Then in main.js I have:
require.config({
baseUrl: "./modules",
waitSeconds: 10,
packages: [
{
name: "something not used yet",
location: "something not used yet",
main: "something not used yet"
}
]
});
require(['game'], function (Game)
{
var game = new Game();
game.begin();
});
Rest I already showed in the beginning.
I have main.html and main.js together in the build folder and all the others in build/modules folder.
Problem was the most ridiculous thing ever and I wasted way to much time to figure out something this obvious...
For some reason I completely forgot to wait for the image to load and kept using it before it is even loaded, and the complicated (for me at least) structure when using requirejs made it hard to pinpoint that mistake.
Also without requirejs the code worked because image loaded so fast, it was ready before the next function started even without onload, however when I switched to requirejs I guess it either slowed down, or the asynchronous nature of it created the problem.
Anyway, solved by simple onload handler.

Categories

Resources