How to fix images not loading in phaser.js - javascript

Whenever I try to load images into phaser they always appear as a green box on my screen?
I've not only tried the root file path like normal, but also every file path imaginable, but it still never works?

I'm assuming you've already set up a web server.. Did you look at developer tools and check if there are any errors? On Google Chrome, right click your web page and hit inspect. Navigate to the Consoles Tab and look for errors. Be sure to also Log XMLHttpRequests, as these will indicate when the request for said image has been fulfilled (just click the Log XMLHttpRequests checkbox).
Did any of the above solutions work for you? For me, I've used a Simple HTTP Server with Python. I was referencing my images correctly and had my web server hosted correctly. When using developer tools, there were no error messages.. I was banging my head against the wall for hours. The Phaser API was not able to tell what the local directory (http://192.168.0.2:8080/) was from the webpage from some reason.
I fixed my issue by using the following path for my images:
'http://192.168.0.2:8080/assets/sky.png'
where 192.168.0.2 was my local IP address hosting the server & 8080 was the port I was using for communications
Alternative to adding that lengthy file path for each of your images, you can call the this.load.setBaseURL('http://192.168.0.2:8080') function in combination with what you already have.
For example, see the following code:
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 200 }
}
},
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
console.log('preload');
this.load.setBaseURL('http://192.168.0.2:8080');
this.load.image('bombP','bowmb.png');
this.load.image('einMary','/bowmb.png');
}
function create ()
{
console.log('create');
this.add.image(126, 119, 'bombP');
this.add.image(222,269,'einMary');
//var s = game.add.sprite(80,0,'einMary');
//s.rotation=0.219;
}

I should start by checking those two points below :
Check if the image has the right path to the file
Check if the 'key' you are using is the right one

Related

Take desktop screenshot with Electron

I am using Electron to create a Windows application that creates a fullscreen transparent overlay window. The purpose of this overlay is to:
take a screenshot of the entire screen (not the overlay itself which is transparent, but the screen 'underneath'),
process this image by sending the image as a byte stream to my python server, and
draw some things on the overlay
I am getting stuck on the first step, which is the screenshot capturing process.
I tried option 1, which is to use capturePage():
this.electronService.remote.getCurrentWindow().webContents.capturePage()
.then((img: Electron.NativeImage) => { ... }
but this captures my overlay window only (and not the desktop screen). This will be a blank image which is useless to me.
Option 2 is to use desktopCapturer:
this.electronService.remote.desktopCapturer.getSources({types: ['screen']}).then(sources => {
for (const source of sources) {
if (source.name === 'Screen 1') {
try {
const mediaDevices = navigator.mediaDevices as any;
mediaDevices.getUserMedia({
audio: false,
video: { // this specification is only available for Chrome -> Electron runs on Chromium browser
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: source.id,
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,
maxHeight: 720
}
}
}).then((stream: MediaStream) => { // stream.getVideoTracks()[0] contains the video track I need
this.handleStream(stream);
});
} catch (e) {
}
}
}
});
The next step is where it becomes fuzzy for me. What do I do with the acquired MediaStream to get a bytestream from the screenshot out of it? I see plenty of examples how to display this stream on a webpage, but I wish to send it to my backend. This StackOverflow post mentions how to do it, but I am not getting it to work properly. This is how I implemented handleStream():
import * as MediaStreamRecorder from 'msr';
private handleStream(stream: MediaStream): void {
recorder.stop()
const recorder = new MediaStreamRecorder(stream);
recorder.ondataavailable = (blob: Blob) => { // I immediately get a blob, while the linked SO page got an event and had to get a blob through event.data
this.http.post<Result>('http://localhost:5050', blob);
};
// make data available event fire every one second
recorder.start(1000);
}
The blob is not being accepted by the Python server. Upon inspecting the contents of Blob, it's a video as I suspected. I verified this with the following code:
let url = URL.createObjectURL(blob);
window.open(url, '_blank')
which opens the blob in a new window. It displays a video of maybe half a second, but I want to have a static image. So how do I get a specific snapshot out of it? I'm also not sure if simply sending the Javascript blob format in the POST body will do for Python to be correctly interpret it. In Java it works by simply sending a byte[] of the image so I verified that the Python server implementation works as expected.
Any suggestions other than using the desktopCapturer are also fine. This implementation is capturing my mouse as well, which I rather not have. I must admit that I did not expect this feature to be so difficult to implement.
Here's how you take a desktop screenshot:
const { desktopCapturer } = require('electron')
document.getElementById('screenshot-button').addEventListener('click', () => { // The button which takes the screenshot
desktopCapturer.getSources({ types: ['screen'] })
.then( sources => {
document.getElementById('screenshot-image').src = sources[0].thumbnail.toDataURL() // The image to display the screenshot
})
})
Using 'screen' will take a screenshot of the entire desktop.
Using 'windows' will take a screenshot of only the application.
Also refer to these docs: https://www.electronjs.org/docs/api/desktop-capturer
desktopCapturer only takes videos. So you need to get a single frame from it. You can use html5 canvas for that. Here is an example:
https://ourcodeworld.com/articles/read/280/creating-screenshots-of-your-app-or-the-screen-in-electron-framework
Or, use some third party screenshot library available on npm. The one I found needs to have ImageMagick installed on linux, but maybe there are more, or you don't need to support linux. You'll need to do that in the main electron process in which you can do anything that you can do in node.
You can get each frame from taken video like this:
desktopCapturer.getSources({
types: ['window'], thumbnailSize: {
height: 768,
width: 1366
}
}).then(sources => {
for (let s in sources) {
const content = sources[s].thumbnail.toPNG()
console.log(content)
}
})

granim.js does not 'see' images when site is on gh-pages while it's OK when it is locally rendered

recently tried to modify one of my webpages with granim.js. I'd like to have
something like this - third example with forest
Unfortunately while it works perfectly during development on my local machine it doesn't work on gh-pages. It throws an error
Error: Granim: The image source is invalid.
And displays only gradient and not gradient image.I have checked also option with full path from gh-pages:
https://github.com/Kiszuriwalilibori/portfolio_granim/blob/master/project_images/moon.jpg
and few similar. None of them works, always the same error.
Examples of granim use bot full paths and local paths, so expected that any of tried paths will work. But not. Here is the part of my code responsible for granim:
window.addEventListener('load', (event) => {
console.log('page is fully loaded');
var granimInstance = new Granim({
element: 'canvas',
direction: 'top-bottom',
isPausedWhenNotInView: true,
image: {
source: '../project_images/moon.jpg',
blendingMode: 'multiply'
},
states: {
"default-state": {
gradients: [
['#29323c', '#485563'],
['#FF6B6B', '#556270'],
['#80d3fe', '#7ea0c4'],
['#f0ab51', '#eceba3']
],
transitionSpeed: 7000
}
}
})
});
Here's link to not working properly item:
https://kiszuriwalilibori.github.io/portfolio_granim/#Home
Has anyone an idea what's wrong? As written at the beginning on local machine it renders perfectly. That is not the only image used by that page (the rest renders OK; but the only used by granim).

Node Webshot Screenshot of Angular JS Page does not wait for page load

I am using node-webshot utility to capture screenshot of an angularJS based website.
I have the following code which is partially working.
const webshot = require('webshot');
var options = {
streamType: 'png',
windowSize: {
width: 2048,
height: 2048
},
shotSize: {
width: 'all',
height: 'all'
}
};
webshot('URL here', 'image.png', options, function(err) {
if(err){
console.log("An error ocurred ", err);
}
else{
console.log("Job done mate :)")
}
});
It works fine for simple websites like google.com e.t.c, but the only problem is that the angular js website i am trying to fetch information from loads the default page first, then loads some additional bits (Forms, UI stuff) e.t.c after few seconds since it makes some http calls in the background.
I have tried using renderDelay property and set it to a large value. it does wait for that time, but still image is just a blank image.
As per their doucmentation set this
takeShotOnCallback false Wait for the web page to signal to webshot
when to take the photo using window.callPhantom('takeShot');
Now i can put this takeShotOnCallback in my properties above, but in the angular app, when i try to write this window.callPhantom, it gives me the error that method doesn't exist.
So how should i use this?
Another broader question is, does Node webshot is the right tool to capture screenshot for Angular 6 website. Or should i look for some other solution.

Cordova camera saves to gallery even on false

I'm in a really nasty situation...
My client wants a Cordova application in Ionic Framework v1, and it's imperative that the camera does not save images to gallery. However, when I set the parameter for saving to gallery to false, it is still saving to gallery.
The problem occurs on Android when you take a photo and cancel it. It then saves that picture to gallery and sometimes even saves all other pictures after that.
I would really welcome any kind of help; All I've found so far are some solutions that I find really hard to understand since my knowledge of Java is zero.
Here is my JS code
function capturePhoto() {
var maxDimension = 1280;
var options = {
quality: 80,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
correctOrientation: true,
targetWidth: maxDimension,
targetHeight: maxDimension,
saveToPhotoAlbum: false
};
This is for camera options.
$cordovaCamera.getPicture(options).then(function (imageData) {
var src = "data:image/jpeg;base64," + imageData;
$scope.photoPreviewSrc = src;
}).catch(function (err) {
});
}
I have checked with your code using cordova. It works fine as expected.
Verify your app in other device once.
I haven't checked it on ionic platform.
You may want to try running something like the following after you receive the image data:
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}
From the docs: "camera.cleanup() Removes intermediate image files that are kept in temporary storage after calling camera.getPicture. Applies only when the value of Camera.sourceType equals Camera.PictureSourceType.CAMERA and the Camera.destinationType equals Camera.DestinationType.FILE_URI."
The above relates directly to your use case.
Is it really going to the photo gallery, or just showing up in Android's photo app? The Android default photo browser will show all photos, screenshots, etc. It will also even show just random images - that other Apps may have on the file system, but that aren't photos.
Since in cordova, you don't have great control of the OS, you can use a work around: You can place the images in a hidden directory (starting with a . such .appdata) and this will prevent Android from automatically seeing the images from the "Gallery" app. I had this problem in an Ionic App and solved it that way.

Phantomjs: take screenshot of the current page?

I'm trying to use Phantomjs to capture a screenshot from the same page that the user is on.
For example, A user is on my-page.html and has made some changes to the elements of this page, now I need to take a screenshot of an element (DIV) inside this page (my-page.html) and save it.
I found a few examples of Phantomjs and php which I tested and worked on my server and it stores the image on my server too BUT all of the examples I found are for taking screenshots of external pages/URLs and not the 'current page'.
This is fairly a straight forward process in Html2canvas but the quality of the produced image is not good at all so I decided to use Phantomjs to produce higher quality screenshots AND also it allows me to zoom in on the page.
Here is a simple example of using Phantomjs for taking screenshot of External URL's:
var system = require("system");
if (system.args.length > 0) {
var page = require('webpage').create();
page.open(system.args[1], function() {
//viewportSize being the actual size of the headless browser
page.viewportSize = { width: 3000, height: 3000 };
//the clipRect is the portion of the page you are taking a screenshot of
page.clipRect = { top: 0, left: 0, width: 3000, height: 3000 };
page.zoomFactor = 300.0/72.0;
var pageTitle = system.args[1].replace(/http.*\/\//g, "").replace("www.", "").split("/")[0]
var filePath = "img/" + pageTitle + '.png';
page.render(filePath);
console.log(filePath);
phantom.exit();
});
}
Could someone please let me know if this is possible at all?
EDIT (Answer to my own question),
it turns out that you cannot take a screenshot of the current page if the page's elements have been edited by the user on the live basis. the only screenshots you can take with phantomjs is a bare bone of the page.
Reason: phantomjs is a headless browser and uses QtWebKit which runs on the server and it is not a javascript library same as html2canvas.
Explained and experienced by others HERE:
Another use case that is an issue for a project I’m working on is that you need drag and drop. Headless drivers have some basic functionality, but if you need to be able to set precise coordinates you’re stuck with Selenium.
For taking screenshot of current page you must pass the correct URL to Phantom script
Syntax :
phantomjs <"Phantom code url(as in documentation report.js)"> <"page url of which you want to take scrrenshot"> <"result saving url">
Now assuming you are passing correct URL :
In my case I was unable to take screenshot of my page as there was a spring security annotation to it, so it was not letting me to proceed so Please check for any security you added to your page if yes then remove it and then try again.
If case 1 does not apply to you surely there is an problem with URL you are passing please double check it.
Please let me know if problem still persist please post any errors(if occurring) you are getting.

Categories

Resources