Image onload not being called in vue - javascript

I am trying to build a Vue App and I am new to Vue, I am trying to load an image at runtime in Js/Ts with the code below
console.log("code is being called");
let image = new Image();
image.onload = (event) => {
console.log("image loaded");
}
image.src = "static/prison_tileset.png";
The code works fine on a regular html file, in Vue however, the onload method isn't being called. The first console.log is being called. I am sure that the image is found because if I manipulate the path to something wrong on purpose I get an error that the file isn't being found. It's just that the onload event isn't being firied.
I'd be very happy if somebody could help me with that!

I've gotten it to work now! I will answer the question myself as best as I can. To use local assets in view you have to load them via Webpack like this:
const Logo = require("../assets/logo.png");
this.image.src = Logo;
If you also happen to use electron you have to set the webSecurity in your entry file to false for electron to be allowed to access local files.

Related

Javascript Phaser3 Assets Not Loading In Create Function

I'm trying to do what seems to be basic image loading into my phaser3 game outside Phaser's preload function, but nothing is working.
I tried:
Lazy loading function in my utils.js:
dynImgLoader(textureKey,x,y,asset)
{
let loader = new Phaser.Loader.LoaderPlugin(this.scene);
loader.image(textureKey,asset);
loader.once(Phaser.Loader.Events.COMPLETE, ()=>
{
console.log('sprite ready for usage');
})
loader.start();
}
When called it still gives me the default phaser asset image (not loaded)
I tried what this tutorial told me in index.js in create function:
this.load.image('arc_red', arc_red);
this.load.onLoadComplete.add(this);
this.load.start();
Still does not work.
Question:
How do I "dynamically" load assets for a multiplayer web socket game without using the preload function? And why is it that I am doing wrong?
If you use this code in the create function (or other non preload functions) it should work:.
this.load.image(key, url); // add task
this.load.once('complete', callback, scope); // add callback of 'complete' event
this.load.start(); // start loading
I got it from this documentation, and it works in my demo code.
Here a working example on Phaser.io

Vue.js/Nuxt.js Load Fallback Image on 404

I am trying to set a default image (placeholder image) in case the image resource is not found (404). I have a dict article which has a value for the key author_image. So that string is not empty but it just can't load that image.
In my template:
<img
:src="article.author_image"
alt="Author Image"
#error="setFallbackImageUrl"
>
In my methods:
methods: {
setFallbackImageUrl(event) {
console.log('Image failed to load, setting fallback.')
event.target.src = '~/assets/icons/avatar.svg'
}
}
I can see in my console log that setFallbackImageUrl is called but the image src is not updated. I made sure that the avatar.svg is actually correct, if I just hard code that over article.author_image that works.
Any suggestions on what I might be doing wrong?
The issue comes while loading your image via vue loader and webpack as the file extensions (.png, .svg, etc) are not module requests (read more about handling assets with vue loader).
You'll need to wrap it in the require to access it. the example by #Toni Michel Caubet works because he is using a link.
This Works for me.
methods: {
setFallbackImageUrl(event) {
console.log('Image failed to load, setting fallback.')
event.target.src = require(`~/assets/icons/${'avatar' + '.svg'}`)
}
}
Note: it's not needed to wrap the image in "${'avatar' + '.svg'}" i just removed my dynamic values and added "avatar".
Just in case someone is hitting a brick wall with webpack (files from assets/static)
The accepted answer from here should resolve it:
Dynamic img src URL with "OR" statement not working properly in NUXT component

get image size before upload in React

The desired results have been done in vanilla here
To be clear, I won't be using alert(), I'd like to place the dimensions in the state object.
How would I recreate this code in React under the OnChange() event handler?
React is still JavaScript, everything you do in regular js can be done in React. At a high level, React is just the framework that helps you create more modular reusable code.
With that being said, thinking as a React developer, you should create the upload process first get that to work in a separate class. The class could accept an image through its props. Then once that is working correctly you could create a Higher order component that wraps the upload component or rather receives the upload component as a parameter and checks the image size. At this point you can return an Invalid component or just process the image and upload.
You might want to look at a few tutorial on Getting started with React.
This is an excellent start egghead.io
I have a img src that looks something like this:
I was able to solve the problem with code like this
if (e.target.files && e.target.files[0]) {
var img = document.createElement("img");
this.state.backgroundImageFile = e.target.files[0];
img.onload = function () {
debugger;
console.log(this.width + " " + this.height);
});
var reader = new FileReader();
reader.onloadend = function (ended) {
img.src = ended.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}

How can I access the DOM of a <webview> in Electron?

I'm just getting started with Electron, with prior experience with node-webkit (nw.js).
In nw.js, I was able to create iframes and then access the DOM of said iframe in order to grab things like the title, favicon, &c. When I picked up Electron a few days ago to port my nw.js app to it, I saw advice to use webviews instead of iframes, simply because they were better. Now, the functionality I mentioned above was relatively easy to do in nw.js, but I don't know how to do it in Electron (and examples are slim to none). Can anyone help?
Also, I have back/forward buttons for my webview (and I intend on having more than one). I saw in the documentation that I could call functions for doing so on a webview, but nothing I have tried worked either (and, I haven't found examples of them being used in the wild).
I dunno who voted to close my question, but I'm glad it didn't go through. Other people have this question elsewhere online too. I also explained what I wanted to achieve, but w/e.
I ended up using ipc-message. The documentation could use more examples/explanations for the layperson, but hey, I figured it out. My code is here and here, but I will also post examples below should my code disappear for whatever reason.
This code is in aries.js, and this file is included in the main renderer page, which is index.html.
var ipc = require("ipc");
var webview = document.getElementsByClassName("tabs-pane active")[0];
webview.addEventListener("ipc-message", function (e) {
if (e.channel === "window-data") {
// console.log(e.args[0]);
$(".tab.active .tab-favicon").attr("src", e.args[0].favicon);
$(".tab.active .tab-title").html(e.args[0].title);
$("#url-bar").val(e.args[0].url);
$("#aries-titlebar h1").html("Aries | " + e.args[0].title);
}
// TODO
// Make this better...cancel out setTimeout?
var timer;
if (e.channel === "mouseover-href") {
// console.log(e.args[0]);
$(".linker").html(e.args[0]).stop().addClass("active");
clearTimeout(timer);
timer = setTimeout(function () {
$(".linker").stop().removeClass("active");
}, 1500);
}
});
This next bit of code is in browser.js, and this file gets injected into my <webview>.
var ipc = require("ipc");
document.addEventListener("mouseover", function (e) {
var hoveredEl = e.target;
if (hoveredEl.tagName !== "A") {
return;
}
ipc.sendToHost("mouseover-href", hoveredEl.href);
});
document.addEventListener("DOMContentLoaded", function () {
var data = {
"title": document.title,
"url": window.location.href,
// need to make my own version, can't rely on Google forever
// maybe have this URL fetcher hosted on hikar.io?
"favicon": "https://www.google.com/s2/favicons?domain=" + window.location.href
};
ipc.sendToHost("window-data", data);
});
I haven't found a reliable way to inject jQuery into <webview>s, and I probably shouldn't because the page I would be injecting might already have it (in case you're wondering why my main code is jQuery, but there's also regular JavaScript).
Besides guest to host IPC calls as NetOperatorWibby, it is also very useful to go from host to guest. The only way to do this at present is to use the <webview>.executeJavaScript(code, userGesture). This api is a bit crude but it works.
If you are working with a remote guest, like "extending" a third party web page, you can also utilize webview preload attribute which executes your custom script before any other scripts are run on the page. Just note that the preload api, for security reasons, will nuke any functions that are created in the root namespace of your custom JS file when your custom script finishes, however this custodial process will not nuke any objects you declare in the root. So if you want your custom functions to persist, bundle them into a singleton object and your custom APIs will persist after the page fully loads.
[update] Here is a simple example that I just finished writing: Electron-Webview-Host-to-Guest-RPC-Sample
This relates to previous answer (I am not allowed to comment): Important info regarding ipc module for users of Electron 1.x:
The ipc module was split into two separate modules:
ipcMain for the main process
ipcRenderer for the renderer process
So, the above examples need to be corrected, instead of
// Outdated - doesn't work in 1.x
var ipc = require("ipc");
use:
// In main process.
var ipcMain = require('electron').ipcMain
And:
// In renderer process.
var ipcRenderer = require('electron').ipcRenderer
See: http://electron.atom.io/blog/2015/11/17/electron-api-changes section on 'Splitting the ipc module'

Moving created files with JXA

I'm new to JXA scripting, but I'm attempting to troubleshoot some older scripts currently in place here at work. They loop through an InDesign document and create several PDFs based on it. Previously, they would be stored in a folder called "~/PDFExports". However, this doesn't work with 10.10.
If I change the code to just place the PDFs in "~/", it works fine. From there, I'd like to move the files to "~/PDFExports", but I can't seem to find an answer on how to do that. I've seen things about making calls to ObjC, or to call Application('Finder'), but neither work - they both return undefined.
Am I just missing something basic here, or is it really this hard to simply move a file with JXA?
EDIT: Some syntax for how I'm creating the folder in question and how I'm attempting to work with Finder.
//This is called in the Main function of the script, on first run.
var exportFolder = new Folder(exportPath);
if(!exportFolder.exists) {
exportFolder.create();
}
//This is called right after the PDF is created. file is a reference to the
actual PDF file, and destination is a file path string.
function MoveFile(file,destination){
var Finder = Application("Finder");
Application('Finder').move(sourceFile, { to: destinationFolder });
alert("File moved");
}
Adobe apps have long included their own embedded JS interpreter, JS API, and .jsx filename extension. It has nothing to do with JXA, and is not compatible with it.
InDesign's JSX documentation:
http://www.adobe.com/devnet/indesign/documentation.html#idscripting
(BTW, I'd also strongly advise against using JXA for Adobe app automation as it has a lot of missing/broken features and application compatibility problems, and really isn't fit for production work.)
Here's the link to Adobe's InDesign Scripting forum, which is the best place to get help with JSX:
https://forums.adobe.com/community/indesign/indesign_scripting
You could use Cocoa to create the folder
var exportFolder = $.NSHomeDirectory().stringByAppendingPathComponent("PDFExports")
var fileManager = $.NSFileManager.defaultManager
var folderExists = fileManager.fileExistsAtPath(exportFolder)
if (!folderExists) {
fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(exportFolder, false, $(), $())
}
and to move a file
var success = fileManager.moveItemAtPathToPathError(sourceFile, destinationLocation, $());
if (success) alert("File moved");
Consider that destinationLocation must be the full path including the file name
and both sourceFile and destinationLocation must be NSString objects like exportFolder
Could it be that the folder is missing ? Could be your reference to the folder object not valid ? Any syntax to show ?
I will share some of what I learned about JXA move and duplicate methods. I am not a professional programmer just an attorney that is passionate about automation. My comments come from much trial and error, reading whatever I could find online, and A LOT of struggle. The move method does not work well with Finder. Use the System Events move method instead. The duplicate method in Finder works just fine. The duplicate method does not work well in system events. This is a modified snippet from a script I wrote showing move() using System Events.
(() => {
const strPathTargetFile = '/Users/bretfarve/Documents/MyFolderA/myFile.txt';
const strPathFolder = '/Users/bretfarve/Documents/MyFolderB/';
/* System Events Objects */
const SysEvents = Application('System Events');
const objPathFolder = SysEvents.aliases[strPathFolder];
SysEvents.move(SysEvents.aliases.byName(strPathTargetFile), {to: objPathFolder});
})();

Categories

Resources