processing.js loadImage() - image

I've made a processing.js webpage that i'm using to put a platformer game on, so i've got the code already planned out. Now I just have to put it on a webpage. Right now I can make the background red, but when I went to put the code in, I realised that it was't drawing any images. I looked it up, and the image method processing.js uses is very different to what I was doing. It still won't work.
Here is my processing.js code inside the HelloWeb.pde file:
preload =
"file:///E:/Extra%20Curricular/STEM%20Videogame/Art/BlackKingIdle.png";
//note that the E drive is my USB. I don't know if it will have an effect?
//AI Codes
int wolfX = 310;
int wolfY = 200;
int wolfHealth = 50;
//Health
int kingHealth = 100;
int dragon = 500;
//LV design
int floorHeight = 300;
int lvlNum = 1;
//movement (x)
int maxSpeed = 6.25;
int xForce = 0;
int kingXPos = 947.5;
//movement (y)
int kingYPos = floorHeight + 50;
int yForce = -15;
int jumping = false;
void setup() {
size(1895, 800);
background(255, 0, 0);
}
void draw() {
if (lvlNum != 0) {
PImage kingIdle = loadImage("file:///E:/Extra%20Curricular/STEM%20Videogame/Art/BlackKingIdle.png")
}
};
And the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Hello Web - Processing.js Test</title>
<script src="processing.min.js"></script>
</head>
<body>
<h1>Processing.js Test</h1>
<p>This is my first Processing.js web-based sketch:</p>
<canvas data-processing-sources="HelloWeb.pde" width="1895" height="800" style="border:4px solid"></canvas>
</body>
</html>

You should get into the habit of posting an MCVE. Try to narrow your problem down to as few lines as possible. For example this code demonstrates your problem:
/* #pjs preload="C:\\Users\\Kevin\\Desktop\\August 1, 2016\\cropped\\Sky4.JPG"; */
PImage myImage;
void setup(){
size(200,200);
myImage = loadImage("C:\\Users\\Kevin\\Desktop\\August 1, 2016\\cropped\\Sky4.JPG");
}
void draw(){
image(myImage, 50,50, 100,100);
}
You should also get into the habit of checking out your JavaScript console. There you'll see any errors you're getting. If you look there, you should see an error that says "(index):1 Not allowed to load local resource".
And that error says it all. You aren't allowed to access local files from a webpage, even if you're running that webpage locally.
Your Processing.js webpage is being served by a local webserver. Processing handles this for you, which is nice, but that webserver can only touch files that you've imported into your sketch directory. Do this through the sketch menu in the Processing editor, or you can manually add a data folder to your sketch directory, and then put your images in there. Then just refer to the images relative to the sketch.
Two lines in my example code would change:
/* #pjs preload="Sky4.JPG"; */
myImage = loadImage("Sky4.JPG");
If you don't want to put your images in your sketch directory, then you're going to have to use your own webserver. You can run one locally, or you can upload your images to an image host and use the url in your code.

Related

Displaying UnSplash image URL's on Processing Sketch

I am trying to display a random image URL retrieved via the UnSplash API on a processing screen. There are two issues I think: 1) the url delivered does not have a supported extension such as .jpg etc. It looks like this for example:
https://images.unsplash.com/photo-1672710509828-c971003d3533?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=Mnw0MDM3NDd8MHwxfHJhbmRvbXx8fHx8fHx8fDE2NzQ5MzI4OTM&ixlib=rb-4.0.3&q=80&w=400
I also imagine that an issue might be that the image is not local?
Can anyone help me with this?
Tracy
PImage IMG;
void setup () {
size(1000, 1000);
background (255);
IMG = loadImage("https://images.unsplash.com/photo-1672710509828-c971003d3533?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=Mnw0MDM3NDd8MHwxfHJhbmRvbXx8fHx8fHx8fDE2NzQ5MzI4OTM&ixlib=rb-4.0.3&q=80&w=400");
}
void draw() {
image(IMG, 0, 0);
}
I get an error saying cannot load because it does not have a typical image extension.
Thanks for the help.
One workaround is to add your own URL encoded variable with the sole purpose of ending the URL with ".jpg"
Here's a basic example:
PImage img;
void setup(){
size(400, 600);
noLoop();
String originalURL = "https://images.unsplash.com/photo-1672710509828-c971003d3533?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=Mnw0MDM3NDd8MHwxfHJhbmRvbXx8fHx8fHx8fDE2NzQ5MzI4OTM&ixlib=rb-4.0.3&q=80&w=400";
img = loadImage(originalURL + "&p5=image.jpg");
}
void draw(){
image(img, 0, 0);
}

How to fade in UI image in Unity

I want to fadein a UI image from transparent(alpha=0) to alpha=1, i thought my approach should be right, but it doesn't work, the image is not changing.
This is the code that i tried for doing that:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Fadein : MonoBehaviour {
public float FadeRate;
private Image image;
private float targetAlpha;
// Use this for initialization
void Start()
{
image = GetComponent<Image>();
Material instantiatedMaterial = Instantiate<Material>(image.material);
image.material = instantiatedMaterial;
targetAlpha = image.material.color.a;
Invoke("startFadein", 1);
}
IEnumerator FadeIn()
{
targetAlpha = 1.0f;
Color curColor = image.material.color;
while (Mathf.Abs(curColor.a - targetAlpha) > 0.0001f)
{
curColor.a = Mathf.Lerp(curColor.a, targetAlpha, FadeRate * Time.deltaTime);
image.material.color = curColor;
yield return null;
}
}
void startFadein()
{
StartCoroutine(FadeIn());
}
}
The image is not changing. But i tried fadeout by using this code, from 1 to 0, it just worked, i have no idea why the fadein doesn't work?
image.material.color is not what you think it is
With a few debug lines I was able to determine that the image material's alpha reports that it is 1 even when I set the image color multiplier to 0.
If I override the curColor to have a 0 and let the loop do its thing, the image never appears either.
This is because this:
Is not image.material.color. It's image.color.
Thus your fixed code would be:
IEnumerator FadeIn() {
targetAlpha = 1.0f;
Color curColor = image.color;
while(Mathf.Abs(curColor.a - targetAlpha) > 0.0001f) {
Debug.Log(image.material.color.a);
curColor.a = Mathf.Lerp(curColor.a, targetAlpha, FadeRate * Time.deltaTime);
image.color = curColor;
yield return null;
}
}
Additionally a few other things:
Your code does not lerp the color linearly. I'm sure you knew that, and you're probably fine with that, but I figured I'd point it out.
You don't need Invoke("startFadein", 1);. You can just call StartCoroutine(FadeIn()); and put yield return new WaitForSeconds(1) at the top.
Your image will never actually reach the target value, it'll be close, but not equal. You can fix this by putting curColor.a = targetAlpha; image.color = curColor; after the while loop.

Variable I did not make is coming up in the console p5

I've had this error message "TypeError: a is undefined" for a while and I finally narrowed it down to a few lines of code in my project. I've created a smaller project from the original to demonstrate my problem:
new p5();
var particle = function(X, Y, C, Kind, Fun) {
this.pos = createVector(X, Y);
this.vel = createVector(0, 0);
this.accel = createVector(0, 0);
this.col = C;
this.isDead = false;
this.kind = Kind;
this.affect = Fun;
};
function setup() {
createCanvas(window.innerWidth, window.innerHeight);
};
var particles = new Array(new particle(1, 1, color(1, 1, 1), function () {
cosole.log("your mamma");
}));
function draw() {
};
If I run this in a browser, I get the error message mentioned above. In case you were wondering what my html looks like, here it is:
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="p5.min.js"></script>
<script src="p5_test.js"></script>
</head>
<style>
body {margin: none; padding: none;}
</style>
<body></body>
</html>
Any suggestions??
It looks like you're trying to use on-demand global mode to get around the restriction of not being able to use P5 functions until after setup() is called. I would expect your code to work.
However, when I run the code, I get this error:
Uncaught TypeError: Cannot read property '_colorMode' of undefined
at new p5.Color (p5.js:6482)
at p5.color (p5.js:6174)
at sketch.js:17
You're using the minified version of the library, so variable names aren't really useful. I'm using the unminified version, so I can see that the actual problem is that the _colorMode variable can't be found.
Tracing through the code, we see that your code calls the color() function, which hits line 6174 of P5.js:
return new p5.Color(this._renderer, arguments);
Which calls the p5.Color constructor, which hits line 6482 of P5.js:
this.mode = renderer._colorMode;
From this, we can see that the renderer variable is undefined, and when we try to access its _colorMode variable, we get the error.
So, it looks like P5's internal renderer variable is not defined, even though you're using on-demand global mode. The on-demand global mode gives you access to simple functions like random(), but it doesn't give you access to functions that require a renderer to have been initialized.
To fix your problem, just move your initialization into your setup() function:
var particle = function(C) {
this.col = C;
};
var particle;
function setup() {
createCanvas(window.innerWidth, window.innerHeight);
particle = new particle(color(1, 1, 1));
}
function draw() {
}
Note that you can also get rid of the new p5() at the top of your code, since it wasn't really helping you at all. Also note that I've simplified your code for the purpose of creating a MCVE, but the same ideas should hold true for your main project.

Networking rotation sync

My Unity version is 5.2.3f1, I m trying to sync the rotation of a child gameobject, in local works perfectly fine but it doesnt show up in other clients. I tried everything I could find and nothing.
The reason of this is to rotate a FPS body, so, I m trying to rotate Spine2 (Rotate the camera is not my best solution). I m using a Mixamo character to test, in the end I will have Mixamo auto-rigged charscters so everything I make here will be compatible.
I tried to use the Network Transform Rigidbody 3D and it only sync the character itself, not Spine2, I have tried Network Transform Child, and an official skeleton sync.
In the script part, I have tried a lot of things, the most promising one was this:
[SyncVar]
private Quaternion syncPlayerRotation;
[SerializeField]
private Transform playerTransform;
[SerializeField]
private float lerpRate = 15f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void LateUpdate () {
TransmitRotations();
LerpRotations();
}
void LerpRotations()
{
if (!isLocalPlayer)
playerTransform.localRotation = Quaternion.Lerp(playerTransform.localRotation, syncPlayerRotation, Time.deltaTime * lerpRate);
}
[Command]
void CmdProvideRotationsToServer(Quaternion playerRot)
{
syncPlayerRotation = playerRot;
}
[Client]
void TransmitRotations()
{
if (isLocalPlayer)
{
CmdProvideRotationsToServer(playerTransform.localRotation);
}
}
Its from UNET tutorial series on youtube, Gamer To Game Developer user.
I attached it to Spine2 and still dont work, but when I attached it to the main character, it worked.
Also tried this:
void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
{
Vector3 syncPosition = Vector3.zero;
if (stream.isWriting)
{
syncPosition = Spine.GetComponent<Rigidbody>().position;
stream.Serialize(ref syncPosition);
}
else
{
stream.Serialize(ref syncPosition);
Spine.GetComponent<Rigidbody>().position = syncPosition;
}
}
But I think it was for an older version of Unity.
To make the rotations I m using A Free Simple Smooth Mouselook
I edited it, this lines:
if (Input.GetMouseButton(1))
{
var xRotation = Quaternion.AngleAxis(-_mouseAbsolute.y, targetOrientation * Vector3.forward);
transform.localRotation = xRotation;
}
else
{
var xRotation = Quaternion.AngleAxis(-_mouseAbsolute.y, targetOrientation * Vector3.right);
transform.localRotation = xRotation;
}
Basicly, I changed Vector3.right to Vector3.forward and converted the Vector3.right only if the right mouse button is not pressed. The script is attached to Spine2 and its activated on the start if(isLocalPlayer) by script.
There's a pic of the current hierarchy:
(some cameras are there only to test, the main camera is FirstPersonCamera, extracted from the standard assets)
I noticed that if I debug log the Spine2 rotation, it only gives me values from 0 to 1.

Adding screenshot functionality to a firefox extension

Is there a cross-platform approach to taking screenshots from a firefox extension?
Ideally I'd like to be able to take a screenshot of a dom element (irrespective of whether it's visible on the page or not), something like:
var screenshot = screenshot(document.getElementById('example');
Any pointers or suggestions would be nice, searching https://developer.mozilla.org/ only yields screenshots they've used in various guides.
After examining the code of several extensions. I took the following approach (to take a snapshot of a particular dom element). This can be used in a Firefox extension to take screenshots of the whole page, to take screenshots of the browser window and to take screenshots of a particular dom element (and all of its child nodes):
Add canvas to xul.
Find dimensions and top-left co-ordinates of element.
Copy portion of window to canvas.
Convert canvas to base64 PNG file.
function getElementScreenshot(elm) {
var x = findPosX(elm);
var y = findPosY(elm);
var width = elm.clientWidth;
var height = elm.clientHeight;
var cnvs = document.getElementById("aCanvas");
cnvs.width = width;
cnvs.height = height;
var ctx = cnvs.getContext("2d");
// To take a snapshot of entire window
// ctx.drawWindow(mainWindow.content, 0, 0, mainWindow.innerWidth, mainWindow.innerHeight, "rgb(255,255,255)");
ctx.drawWindow(mainWindow.content, x, y, width, height, "rgb(255,255,255)");
return(cnvs.toDataURL());
}
To find top left coordinate of an element
function findPosX(obj) {
var curleft = 0;
if (obj.offsetParent) {
while (1) {
curleft += obj.offsetLeft;
if (!obj.offsetParent) {
break;
}
obj = obj.offsetParent;
}
} else if (obj.x) {
curleft += obj.x;
}
return curleft;
}
function findPosY(obj) {
var curtop = 0;
if (obj.offsetParent) {
while (1) {
curtop += obj.offsetTop;
if (!obj.offsetParent) {
break;
}
obj = obj.offsetParent;
}
} else if (obj.y) {
curtop += obj.y;
}
return curtop;
}
To get access to browser.xul from sidebar
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
mainWindow.gBrowser.addTab(...);
Download one of the many Firefox screen capture extensions, and look at their code to see how they do it. Eg Screengrab, Fireshot, or Page Saver
I guess it would be something like this:
Copy the DOM element in question to a separate iframe or browser (which is not visible to the user)
Paint the window of that iframe onto an html canvas using drawWindow(). Check out the source of the Tab Preview addon to see how this is done.

Resources