Sweetalert2 modal loads briefly before image appears in modal - javascript

I'm using Sweetalert2 to display a modal that has an image inside. Although it works fine, the modal without the image shows for a split second before the image appears. How can I wait until the image fully loads. Here's what I've tried that doesn't work: (loadPage is called when the page loads.)
function loadPage() {
var img = new Image();
img.onload = function () { setTimeout(function () { getToast(); }, 5000); }
img.src = "Images/Save.png";
}
function getToast() {
const Toast = Swal.mixin({
toast: false,
showConfirmButton: true,
confirmButtonText: 'close',
timer: 6000,
imageUrl: 'Images/Save.png',
timerProgressBar: true,
title: 'My message.',
})
Toast.fire({
})
}

The way you're doing it should just work without any flicker. The image is downloaded, cached and on the subsequent requests it should be served from cache. I created a fiddle and could not reconstruct your described issue.
Although I created an alternative approach saving the downloaded image as an dataURI and passing it to your SweetAlert instance. This way you can prevent accidentally downloading the image multiple times.
function loadPage() {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL('canvas');
setTimeout(function () { getToast(dataURL); }, 1000);
canvas = null;
};
img.src = 'http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png';
}
function getToast(dataURL) {
const Toast = Swal.mixin({
toast: false,
showConfirmButton: true,
confirmButtonText: 'close',
timer: 6000,
imageUrl: dataURL,
timerProgressBar: true,
title: 'My message.',
})
Toast.fire({
})
}
loadPage()
Also see the attached fiddle for a working example: https://jsfiddle.net/4sza8u2m/

Related

Dynamically load files to wavesurfer plugin

Hi I want to load an audio file to display digital signals on browser. I am using wavesurfer.js to display digital signals. Could someone help me to display digital signals for dynamically loaded audio file. How to modify my code to able to read system selected audio and display digital signal for it?
javacript:
input.onchange = function(){
var sound = document.getElementById('sound');
var reader = new FileReader();
reader.onload = function(e) {
sound.src = this.result;
sound.controls = true;
sound.display();
// sound.play(); autoplay feature!!
};
reader.readAsDataURL(this.files[0]);
}
var buttons = {
play: document.getElementById("btn-play"),
pause: document.getElementById("btn-pause"),
stop: document.getElementById("btn-stop")
};
// Create an instance of wave surfer with its configuration
var wavesurfer = WaveSurfer.create({
container: '#audio-spectrum',
progressColor: "#03a9f4",
container: document.querySelector('#audio-spectrum'),
backend: 'MediaElement'
});
// Handle Play button
buttons.play.addEventListener("click", function(){
wavesurfer.play();
// Enable/Disable respectively buttons
buttons.stop.disabled = false;
buttons.pause.disabled = false;
buttons.play.disabled = true;
}, false);
wavesurfer.load('http://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3');

Vimeo videos do not load

I would like to use integrated Vimeo videos on a page and have them start playing as soon as the page is loaded and when the first video has finished, the second one starts. In my code I have an array of video ids but my problem is the video does not load.
<div id="headervideo"></div>
<script src="https://player.vimeo.com/api/player.js"></script>
<script>
//====================
document.addEventListener("DOMContentLoaded", function(event) {
var videos = ['240512614', '227735391']; // videos ids
var options = {
width: 640,
loop: true
};
var player = new Vimeo.Player('headervideo', options);
playMovie(player, videos)
})//end function
//====================
var playMovie = function(player, videos) {
if(!videos.length){
return false;
}
var video = videos.shift();
alert (video)
player.loadVideo(videos).then(function(id) {
alert("the video successfully loaded ")
player.getEnded().then(function(ended) {
playMovie(player, videos)
}).catch(function(error) {
console.warn(error)
});
}).catch(function(error) {
console.warn(error);
});
}//end function
//====================
</script>
Your first issue lies in
new Vimeo.Player('headervideo', options);
You cannot create a Vimeo.Player without specifying a video in the options object (or as an html attribute on an associated element).
So, specifying either:
var video = videos.shift();
var options = {
width: 640,
loop: true,
id: video
}
or:
var options = {
width: 640,
loop: true,
id: videos[0]
}
Will let you load the video.
But this will raise your second issue, that playMovie will not wait for your currently playing video to finish, but rather swap the video out immediately. getEnded() is not a synchronously blocking function.
What you want to do is instead listen on the ended event. And also turn of the loop: true as this will disable the ended event
document.addEventListener("DOMContentLoaded", function(event) {
window.videos = ['240512614', '227735391']; // videos ids
var video = videos.shift();
var options = {
width: 640,
loop: false,
id: video
};
window.player = new Vimeo.Player('headervideo', options);
window.player.on('ended', playNext);
window.player.play();
})//end function
//====================
var playNext= function() {
alert('foo');
if(!window.videos.length){
return false;
}
var video = window.videos.shift();
alert (video);
player.loadVideo(video).then(function(id) {
alert("the video "+id+" successfully loaded ");
player.play();
}).catch(function(error) {
console.warn(error)
});
}//end function

Video stream to canvas to image using JavaScript for Project Oxford

I've been able to use Project Oxford, specifically the Emotions API by manually asking a user to upload pictures. However, I'm now looking to do this using a video stream (the webpage shows a live video stream from their webcam and the user can take a snapshot of the stream and then choose to have the emotions API run on that image, which will then run the API and show the scores in a dialogue window - this is the part which I am currently stuck with).
Below I've written the HTML and JavaScript code which sets up the video stream on the webpage and then allows the user to take a snapshot, which then converts the canvas to an image.
<video id="video" width="640" height="480" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>
<img id="file" src = "" alt="Emotions">
<!--input type="file" id="file" name="filename"-->
<button id="btn">Click here</button>
<script>
// Put event listeners into place
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if(navigator.mozGetUserMedia) { // WebKit-prefixed
navigator.mozGetUserMedia(videoObj, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
var dataURL = document.getElementById("canvas");
if (dataURL.getContext){
var ctx = dataURL.getContext("2d");
var link = document.createElement('a');
link.download = "test.png";
var myImage = link.href = dataURL.toDataURL("image/png").replace("image/png", "image/octet-stream");
link.click();
}
var imageElement = document.getElementById("file");
imageElement.src = myImage;
//document.getElementById("file").src = dataURL;
$('#btn').click(function () {
//var file = document.getElementById('file').files[0];
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
data: imageElement,
processData: false
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
})
.fail(function(error) {
//alert(error.getAllResponseHeaders());
alert("Error");
});
});
});
}, false);
</script>
I'm not able to get the API running on the image after it's been converted as a canvas. After reading around, I believe this has something to do with the file extension that's given to the image after it's been converted as a canvas (there is none), as the API only allows for image file types. I believe this might be where the problem lies and any help would be very much appreciated. Many thanks!
This is the code I'm using to upload the picture to a backend API, which then use the .NET SDK after adding some business logic.
It is not the exact same scenario but the Javascript code might help you:
var url = 'Home/upload';
var data = new FormData();
data.append('file', imgData);
var imgData = canvas.msToBlob('image/jpeg');
$.ajax({
type: 'POST',
url: url,
data: data,
processData: false,
contentType: false
})
.done(function (response) {
loading.style.display = "none";
if (response.error != "") {
result.innerText = response.error;
}
else {
result.innerHTML = response.result;
}
})
.fail(function (response) {
alert('Error : ' + response.error);
})
.complete(function (response) {
restartButton.style.display = 'inline-block';
});
The following thread helped me: Pass Blob through ajax to generate a file

android - Selected photo from gallery rotates in landscape in phonegap

I'm using the phonegap file upload to upload files to a server. When i select a portrait photo from the gallery it rotates to landscape
function selectPicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI,correctOrientation : true, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
there is a "correctOrientation" parameter for getPicture (http://docs.phonegap.com/en/edge/cordova_camera_camera.md.html) try setting it to false (or true :D)
Hope this helps

Chrome Extension: Automatically download a screenshot taken with 'chrome.tabs.captureVisibleTab'

I'm new to the world of Chrome extensions / auto-downloading. I have a background page which takes a screenshot of the visible webpage with chrome.tabs.captureVisibleTab(). In my popup I have:
chrome.tabs.captureVisibleTab(null, {}, function (image) {
// Here I want to automatically download the image
});
I've done something similar with a blob before but I'm totally at a loss as to how to download an image as well as how to do it automatically.
In practice, I want my Chrome extension to screenshot + download the image automatically whenever a particular page is loaded (I'm guessing this will have to be achieved by having my content script talk to my background page, correct?)
Yes, as you said you can use Message Passing to get it done. By content scripts to detect the switch on particular pages, then chat with the background page in order to capture screenshot for that page. Your content script should send a message using chrome.runtime.sendMessage, and the background page should listen using chrome.runtime.onMessage.addListener:
Sample codes I created and tested it works with me:
Content script(myscript.js):
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
});
Background.js:
var screenshot = {
content : document.createElement("canvas"),
data : '',
init : function() {
this.initEvents();
},
saveScreenshot : function() {
var image = new Image();
image.onload = function() {
var canvas = screenshot.content;
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
// save the image
var link = document.createElement('a');
link.download = "download.png";
link.href = screenshot.content.toDataURL();
link.click();
screenshot.data = '';
};
image.src = screenshot.data;
},
initEvents : function() {
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello") {
chrome.tabs.captureVisibleTab(null, {format : "png"}, function(data) {
screenshot.data = data;
screenshot.saveScreenshot();
});
}
});
}
};
screenshot.init();
Also keep in mind to register your content script's code and permissions in manifest file:
"permissions": ["<all_urls>","tabs"],
"content_scripts": [
{
"matches": ["http://www.particularpageone.com/*", "http://www.particularpagetwo.com/*"],
"js": ["myscript.js"]
}
]
It captures the screenshot and download the image automatically as .png whenever a particular page is loaded. Cheers!
Here's an alternative to message passing that should accomplish the same:
In my manifest.json
"manifest_version": 3,
"permissions": ["activeTab", "scripting"],
"background": {
"service_worker": "background.js"
},
...
In background.js
const download = (dataurl, filename) => {
const link = document.createElement("a");
link.href = dataurl;
link.download = filename;
link.click();
}
chrome.action.onClicked.addListener((tab) => {
chrome.tabs.captureVisibleTab(async (dataUrl) => {
await chrome.scripting.executeScript({
func: download,
target: { tabId: tab.id },
args: [dataUrl, 'test.png'],
});
});
});

Categories