Create an Image object from scratch? (Javascript) - javascript

I want to create an image object from scratch. Here is the idea:
var image = new Image();
var image2 = new Object();
/* heres where the magic is
\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
if image = image2
alert('sucess');
The goal is that I need to edit the Image object to accept video files. I suppose the solution could also be prototypical if it changed the structure of the Image object appropriately.

function videotr(){
media = document.createElement('video');
media.preload = true;
//media.controls = true;
media.className = 'c1';
media.id = 'it';
document.getElementById('crop').appendChild(media);
//media.loop = true;
//media.autoplay = true;
return media;
}
this works

Related

how do I replace an image with broken link to a default image?

I am not normally one to write JS, but I need this for a little project for my work that displays 4 images on some tv's that management can update. I created a little site that displays the images and need it to refresh the image with new slides every so often as they are updated. This all works fine, but if someone names the image incorrectly it will be a broken link. How can I add a check to see if the image exists and if it doesn't return a default image.
//sleep function
async function sleep(seconds) {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}
async function setImage() {
//get divs by class name
const imageDiv1 = document.querySelector('.image1');
const imageDiv2 = document.querySelector('.image2');
const imageDiv3 = document.querySelector('.image3');
const imageDiv4 = document.querySelector('.image4');
//define const images
const image0 = new Image();
const image1 = new Image();
const image2 = new Image();
const image3 = new Image();
const image4 = new Image();
//define paths
const defaultImage = 'default.png';
const safteyImage = "..\\Safety\\Safety_current.png";
const qualityImage = "..\\Quality\\Quality_current.png";
const omImage = "..\\O&M\\O&M_current.png";
const announcementsImage = "..\\Announcements\\Announcements_current.png";
//set images to paths
image0.src = defaultImage;
image1.src = safteyImage;
image2.src = qualityImage;
image3.src = omImage;
image4.src = announcementsImage;
//add images to canvas
imageDiv1.appendChild(image1);
imageDiv2.appendChild(image2);
imageDiv3.appendChild(image3);
imageDiv4.appendChild(image4);
//infinite loop of updating image.
while(true){
await sleep(5); //only 5 seconds right now for testing.
image1.src = safteyImage + "?" + new Date().getTime();
image2.src = qualityImage + "?" + new Date().getTime();
image3.src = omImage + "?" + new Date().getTime();
image4.src = announcementsImage + "?" + new Date().getTime();
imageDiv1.replaceChild(image1, image1);
imageDiv2.replaceChild(image2, image2);
imageDiv3.replaceChild(image3, image3);
imageDiv4.replaceChild(image4, image4);
}
}
//call setImage on load
window.onload = (event) => {
setImage();
}
I am looking for a way to switch it to a default image within the while loop so it is always checking if it exists or not.
document.getElementsByClassName('.image1').onerror = function() {
document.getElementsByClassName('.image1').src = "default.png";
}
doesnt seem to work for me. I also found a function that checks the status code, but since this is looking into a local file I dont this this approach works, which it didnt.
//check if an image exists, (non working)
function imageExists(image_url){
var request = new XMLHttpRequest();
request.open("GET", image_url, true);
request.send();
request.onload = function() {
imageStatus = request.status;
if(request.status == 200) {
console.log('it exists');
}else{
console.log('nope');
}
}
}
You can listen for the "error" event on the document itself. This obviates the need to attach event listeners on each individual image.
document.addEventListener('error', e => {
e.target.src = 'default.png';
}, true);
Here is the best solution
Use the img tag for the default image:
const image0 = Image();
image0.src = defaultImage;
Then for every image use the object tag, inserting a copy of the default image inside (so that it gets loaded of the object resource fails to load):
const image1 = document.createElement("object");
image1.appendChild(image0.cloneNode());
To set the source of the images use data attribute:
image1.data = safteyImage;
This way if the resource represented by the object tag can't be loaded, the default image gets loaded instead.
by LL

JavaScript object containing multiple Base64 image codes

Project:
Loading screen with Base64 image in Playcanvas (WebGL)
What I try to do:
Change the image when the Website is loaded with other language (index.html?language=xy)
What I already have:
I get the default image in my WebGL loading javascript.
var logo = document.createElement('img');
logo.src = 'here is my base64 code';
splash.appendChild(logo);
logo.onload = function() {
splash.style.display = 'block';
};
I thought it would be the best option to list all languages in an object, and invoke the object with the language that is currently selected.
Why I can't figure it out myself:
As I just started creating javascript projects, I need to lookup many thing, but when I search up my issue I get stuff like this Base64 encode a javascript object
Define all the images in an object
const images = {
'us': 'data:image/jpeg;base64,...',
'nl': 'data:image/jpeg;base64,...',
'fallback': 'data:image/jpeg;base64,...'
}
Parse the query paramters, use a fallback if not given
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
let lanuageKey = params['language'];
if (!images[lanuageKey]) {
lanuageKey = 'fallback';
}
Add the image with desired base64
var logo = document.createElement('img');
logo.src = images[lanuageKey];
document.body.appendChild(logo);
Putting this all together, will give something like the following snippet:
Note 1: Stack Snippets can't read the query params, so you'll need to try this locally
Note 2: Due to the 30k max chars, I had to remove the base64's
const images = {
'us': 'data:image/jpeg;base64...',
'nl': 'data:image/jpeg;base64...',
'fallback': 'data:image/jpeg;base64...'
}
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
let lanuageKey = params['language'];
if (!images[lanuageKey]) {
lanuageKey = 'fallback';
}
var logo = document.createElement('img');
logo.src = images[lanuageKey];
document.body.appendChild(logo);

Google Chromecast subtitle not working

I have this code
var englishSubtitle = new chrome.cast.media.Track(2,chrome.cast.media.TrackType.TEXT);
englishSubtitle.trackContentId = 'english.vtt';
englishSubtitle.trackContentType = 'text/vtt';
englishSubtitle.subtype = chrome.cast.media.TextTrackType.CAPTIONS;
englishSubtitle.name = 'English';
englishSubtitle.language = 'en-US';
englishSubtitle.customData = null;
var tracks = englishSubtitle;
var mediaInfo = new chrome.cast.media.MediaInfo(app.streamState_.manifest);
mediaInfo.contentType = app.streamState_.type;
mediaInfo.metadata = new chrome.cast.media.GenericMediaMetadata();
mediaInfo.customData = null;
mediaInfo.streamType = chrome.cast.media.StreamType.BUFFERED;
mediaInfo.textTrackStyle = new chrome.cast.media.TextTrackStyle();
mediaInfo.tracks = tracks;
mediaInfo.metadata.metadataType = chrome.cast.media.MetadataType.GENERIC;
var activeTrackIds = [2];
var request = new chrome.cast.media.LoadRequest(mediaInfo);
request.autoplay = true;
request.currentTime = 0;
request.activeTrackIds = activeTrackIds;
session.loadMedia(request,onMediaDiscovered.bind( this, 'loadedMedia'), onMediaError);
I want to show subtitle on chromecast. When I want to set activeTracks on the request, I receive an error
Object {code: "session_error", description: "INVALID_PARAMS", details: Object}
The subtitle it doesn't show and the video doesn't play it at all, because of that error.
Am I doing something wrong?
tracks should be an array when you set
mediaInfo.tracks = tracks;
In your case, you should try
var tracks = [englishSubtitle];
and as was said earlier, use SUBTITLES instead of CAPTIONS. Finally make sure you have CORS headers present from your web server even if you are using mp4.
tracks should be stored inside an array
https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.MediaInfo#tracks
Array of non-null chrome.cast.media.Track
Array of Track objects.
mediaInfo.tracks = [englishSubtitle, frenchSubtitle, germanSubtitle]
I've created a simple javascript wrapper for the chromecast SDK:
https://github.com/Fenny/ChromecastJS
Might be worth to check out if you stumble upon more problems, good luck!

EaselJS : I'm trying to understand how Cross Domain works with bitmaps

I'm very new to javascript and EaselJS and I've searched the documentation as well as the questions here and I've learned that my initial problem with my mouse events not working with my bitmaps was because I'm trying to use bitmaps from a filepath on my computer.
I understand now that I need to use img.crossOrigin to allow easeljs to work with these images, but even though I'd added this, I still can't get this to work.
Here's what I have:
function init(){
var canvas = document.getElementById('game'); //assign canvas to variable
var stage = new createjs.Stage(canvas);
var term = new Image();
term.src = 'terminal.png';
term.crossOrigin = "Anonymous";
var oswin = new Image();
oswin.src = 'frame.png';
oswin.crossOrigin = "Anonymous";
var terminal = new createjs.Bitmap(term);
terminal.x = 28;
terminal.y = 36;
terminal.name = "terminal";
stage.addChild(terminal);
var oswindow = new createjs.Bitmap(oswin);
stage.addChild(oswindow);
oswindow.x = 196;
oswindow.y = 5;
oswindow.name = "oswindow";
//hide this bitmap
oswindow.visible = false;
//onclick to unhide the bitmap
terminal.on("click", handleClick);
stage.update();
}
function handleClick(){
oswindow.visible = true;
stage.update();
}
I've added in the crossOrigin and unfortunately, this still doesn't work and I've no idea why because I don't understand cross domain very well despite reading on it. (I'm a beginning programmer)
I work entirely offline right now, just trying to learn, so a way to fix this would be really nice.

How to reference this preloaded image

How would I reference an image preloaded from this javascript? This code comes from the question at
stackoverflow: preload hidden CSS images
<script language="JavaScript">
function preloader()
{
// create object
imageObj = new Image();
// set image list
images = new Array();
images[0]="image1.jpg"
imageObj.src=images[0];
}
</script>
It's a logical error in your code as pointed out by Matt H.
Instead creating a separate Image object for each individual images. You are just creating one object and keep changing the src of that object.
function preloader() {
// counter
var i = 0;
// set image list
images = new Array();
images[0] = "image1.jpg"
images[1] = "image2.jpg"
images[2] = "image3.jpg"
images[3] = "image4.jpg"
//create an array to hold all the Image objects
imageObjs = [];
// start preloading
for (i = 0; i <= 3; i++) {
var imageObj = new Image(); //create new Image object for each image
imageObj.src = images[i]; //set the src of new Image object to current image
imageObjs.push(imageObj); //add the current Image object to the array
}
}
In your code, you are depending on the browser cache as the "preloader". Only the last images[i] source is actually held in the imageObj variable. Just setting the src value of an image will pull it from the browser cache.
A proper method of preload would be to create an array of imageObj image objects. You still reference through `.src', but now you have image objects in Javascript memory rather than the browser cache.

Categories