Surely there are better options, but I was trying this:
images = document.getElementsByTagName("img")
links = []
for (let img of images){
const alt = img.getAttribute("alt")
if( alt && alt.substring("code")){
var save = document.createElement('a');
save.href = img.src
save.download = `${img.src}`
save.click()
break//test with one for now
}
}
from the console. Now instead of automatically downloading it just opens it in a different page and I'd need to manually download.
Any ideas what am I missing?
Related
I have the following code:
let self = this;
this.chunks = [];
const canvas2 = document.getElementById("self-canvas");
let recordStream = canvas2.captureStream(1);
var options;
options = {mimeType: 'video/webm; codecs=vp9'};
this.recorder = new MediaRecorder(recordStream, options);
this.recorder.ondataavailable = function(evt) {
self.chunks.push(evt.data);
};
this.recorder.onstop = function(evt) {
console.log("recorder stopping");
const link = document.createElement('a');
const videoBlob = new Blob(self.chunks, { type: "video/webm" });
console.log("file size: " + videoBlob.size);
const url = URL.createObjectURL(videoBlob);
link.href = url;
link.download = "sample.webm";
document.body.append(link);
link.click(); //if I comment out here I can see the video
};
console.log("finished setting controller")
console.log("recorder starting");
this.recorder.start(10000);
// the recorder.stop is called somewhere else
What it is supposed to do is pretty simple:
I have the element with id "self-canvas" that is showing my camera.
Now I am trying to record the camera and download the video from the browser using MediaRecorder, but for some reason I am unable to download the file.
I am sure that the file is being recorded, and console.log("file size: " + videoBlob.size); does not return empty.
But when I let the code run, instead of downloading the file, it tries to open it on the same window, and I cannot even see the video because the previous window disappears with the data of the recording.
However if I comment out the link.click(); I am able to see the video by opening the link on a new page (without closing the previous one). But it still doesn't download...
I used this as example, what am I doing wrong?
For heaven's sake...
I just added target blank and it worked.
link.href = url;
link.download = "sample.webm";
link.target = '_blank';
Probably because the resources are lost if it tries to open on the same page, and because it doesn't actually download the file if it is not a link "click".
Still, I never saw anyone having to add target blank in their examples like this one.
So I wonder why this is the case only for me...
I'm pretty new to JS and programming altogether so I'm sorry in advance if the explanation is a little sloppy, but I'll try to make it as clear as possible.
So what I'm trying to do is have a JS code that reads and displays (in an HTML page) photos from a PC folder, makes them clickable and on the click it redirects you to a page with the same photo but in high resolution.
Now, I have this piece of code that displays the said pictures, but the thing is I don't seem to be able to figure out how to "connect" it to the pictures and make them clickable. What makes it more difficult is that I'm trying to make all of this code dynamic (as you can see I've done in the below code), so I would like not to have any hardcoded titles of pictures and so on.
var index = 1;
var tempImg = new Image();
tempImg.onload = function(){
appendImage();
}
var tryLoadImage = function(index){
tempImg.src = 'img/' + index + '.jpg';
}
var appendImage = function(){
var img = document.createElement('img');
img.src = tempImg.src;
document.body.appendChild(img)
tryLoadImage(index++);
}
tryLoadImage(index);
Any help is very much appreciated, thank you very much!
You can make your images clickable by adding an onclick function to them. Try something like this:
var appendImage = function(){
var img = document.createElement('img');
img.src = tempImg.src;
img.onclick = e => {
// do something you want to show the full picture like this maybe
var el = document.getElementById("fullpictureid");
if (el && e.target.src) {
el.src = e.target.src;
// so that it sets "src" in <img id="fullpictureid"> for example
}
};
document.body.appendChild(img)
tryLoadImage(index++);
}
I'm using this code to capture images as canvas from a video URL in my site:
var videoId = 'video';
var scaleFactor = 0.55; // increase or decrease size
var snapshots = [];
/**
* Captures a image frame from the provided video element.
*
* #param {Video} video HTML5 video element from where the image frame will be captured.
* #param {Number} scaleFactor Factor to scale the canvas element that will be return. This is an optional parameter.
*
* #return {Canvas}
*/
function capture(video, scaleFactor) {
if(scaleFactor == null){
scaleFactor = 1;
}
var w = video.videoWidth * scaleFactor;
var h = video.videoHeight * scaleFactor;
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
var uniq = 'img_' + (new Date()).getTime();
canvas.setAttribute('id', uniq);
return canvas ;
}
/**
* Invokes the <code>capture</code> function and attaches the canvas element to the DOM.
*/
function shoot(){
var video = document.getElementById(videoId);
var output = document.getElementById('output');
var canvas = capture(video, scaleFactor);
snapshots.unshift(canvas);
output.innerHTML = '' ;
for(var i=0; i<10; i++){
output.appendChild(snapshots[i]);
}
}
My two problems:
1 - Currently, browsers treat <canvas> like they they treat a <div> and this make it impossible to save any generated canvas as an image because when I right-click on each and everyone, it always opens the windows dialog here I have to choose Save image as....
2 - The windows right-click dialog always opens by default the option to save image as transfer.png and I would like to save the image with their ID attribute (var uniq) and a jpg extension.
Example of what I need:
The output canvas is like this: <canvas width="352" height="198" id="img_1575807516362"></canvas>.
I want the right-click to open the windows dialog offering to save image like this img_1575807516362.jpg.
Alternatively, it would be nice tho have a download button for each canvas to export the canvas as an image like this transfer.jpg.
Is it possible to make this work with this code?
Apologies in advance. It took me some time, but I wanted to make sure that I got it working properly. I am not sure if there is a way to do a windows dialog to save to file (Where it pulls up the save as... prompt), but you can definitely create a download button to do this.
Downloading the Image
First, we need to create a download button:
<button onmousedown="download()">Download</button>
Second, we can create a function to download the image with a key.
The easiest way to do this is creating a downloadable <a> tag:
var download = function(){
var link = document.createElement('a'); //Creates an 'a' element
var thisCanvas = document.getElementsByTagName('canvas')[0]; //gets the first canvas element on the page, assuming the canvas you want to download is this element.
link.download = `${thisCanvas.id}.jpeg`; //Gives the download an output link
link.href = thisCanvas.toDataURL("image/jpeg") //Gives the data to the link
link.click(); //Clicks the 'a' element we created
}
If you wanted to ask for user input whether or not they want to download, you can use:
var download = function() {
if (window.confirm("Would you like to download this frame?")) {
var link = document.createElement('a'); //Creates an 'a' element
var thisCanvas = document.getElementsByTagName('canvas')[0]; //Gets the canvas
link.download = `${thisCanvas.id}.jpeg`; //Gives the download an output link
link.href = thisCanvas.toDataURL("image/jpeg") //Gives the data to the link
link.click(); //Clicks the 'a' element we created
}
}
You can always change the name of the image file as well with link.download = imageName + ".jpeg"
Creating A Button in JS
EDIT: If you want to create the button in javascript instead of html, you can do the following:
var createbutton = function() {
var b = document.createElement('button'); //Creates the button
b.onmousedown = function() { //Creates an onmousedown event for the button
download(); //This is the download function above
}
b.innerHTML = "Download"; //Gives the button Text
//Here, you can insert button styles using: b.style
document.body.appendChild(b); //Appends the button to the body
}
You can call this function whenever you need to create the download button. This function creates a button at the end of the body, but you can change the location:
//Where it says document.body.appendChild(b); , replace it with:
document.getElementById(`myCustomId`).appendChild(b);
//This places the button in any element on the page with 'myCustomId'
Canvas onmousedown events, and downloading all images
EDIT (2):
If you have multiple canvases that are created within snapshots, then you can do the following to download all the snapshots:
var download = function(){
var link = document.createElement('a'); //Creates an 'a' element
snapshots.forEach(snap => {
link.download = `${snap.id}.jpeg`; //Gives the download an output link
link.href = snap.toDataURL("image/jpeg") //Gives the data to the link
link.click(); //Clicks the 'a' element we created
});
}
If you want to download one image at a time, you can give them an onmousedown event when you add them. Let's edit the download function to support this:
var download = function(canvas){
var link = document.createElement('a'); //Creates an 'a' element
link.download = `${canvas.id}.jpeg`; //Gives the download an output link
link.href = canvas.toDataURL("image/jpeg") //Gives the data to the link
link.click(); //Clicks the 'a' element we created
}
//We also need to edit the shoot() function
function shoot(){
var video = document.getElementById(videoId);
var output = document.getElementById('output');
var canvas = capture(video, scaleFactor);
canvas.onmousedown = function() {
download(canvas);
}
snapshots.unshift(canvas);
output.innerHTML = '' ;
for(var i=0; i<10; i++){
output.appendChild(snapshots[i]);
}
}
This way whenever you append all of the snapshots, each canvas comes with it's own mousedown event, so clicking on it will return the image. You can even add a confirm box or check if right mouse is clicked here.
Question 2: It doesn't matter where the functions go, only where you call them.
If you have any questions, let me know!
I have an event creation page with image upload. After I select an image, the image is previewed in the browser. When I scroll after the image is added, I see bottom scroll bar stays in the middle of the screen until I focus on an input element. e.g When I focus on description text-area the scroll bar in the middle disappears.
Working version is in jsbin, try selecting an image multiple times. The issue in jsbin:
https://jsbin.com/wigawededo/1/edit?html,css,js,output
Issue on my computer:
When an image is selected I preview it with this code:
function showImage() {
var imageSelector = document.getElementById("image");
var image = document.getElementById("image").files[0];
var reader = new FileReader();
reader.onload = function(e) {
const prevImage = document.querySelector("#previewImage");
if (prevImage) prevImage.parentNode.removeChild(prevImage);
const prevImageLabel = document.querySelector("#previewImageLabel");
if (prevImage) prevImageLabel.parentNode.removeChild(prevImageLabel);
var newImage = document.createElement("img");
newImage.style.maxHeight = "300px";
newImage.style.maxWidth = "300px";
newImage.id = "previewImage";
newImage.src = e.target.result;
var imageLabel = document.createElement("p");
imageLabel.innerHTML = "Preview image:";
imageLabel.id = "previewImageLabel";
imageSelector.parentNode.insertBefore(
imageLabel,
imageSelector.nextSibling
);
imageSelector.parentNode.insertBefore(
newImage,
imageSelector.nextSibling.nextSibling
);
};
if (image) reader.readAsDataURL(image);
else {
const prevImage = document.querySelector("#previewImage");
if (prevImage) prevImage.parentNode.removeChild(prevImage);
const prevImageLabel = document.querySelector("#previewImageLabel");
if (prevImage) prevImageLabel.parentNode.removeChild(prevImageLabel);
}
}
The file selector input has #image id. Note, this code deletes the preview image if there is no file selected.
I am just wondering why this happens. Can you think of a solution? Thanks.
Note: I am using chrome on ubuntu linux
Some of your content must go out of the screen. Try using overflow: hidden or try to decrease width of input/other elements.
I have a javascript widget which fetches articles from Wikipedia through MediaWiki API (http://en.wikipedia.org/w/index.php?title=Main_Page&action=render). It's an app for Samsung Smart TVs. Now the text part works fine, but it won't display any images because the img src is structured like this:
"//en.wikipedia.org/wiki/File:example.jpg"
and I've come to realize by using a PC emulator that the Samsung firmware converts it to this type of full url:
"file://localhost/en.wikipedia.org/wiki/File:example.jpg"
Is it possible to add "http:" to the src so that the app points to the correct links hence displaying both thumbnails and full-size images?
Here's the relevant part of the js code:
UIContents.showImage = function(srcURLFromWikiPage, showHigherResolution) {
// alert("UIContents.fillDescription()");
var cutURL = srcURLFromWikiPage;
//document.getElementById('UIContentsImgFrameiFrame').href = srcURL;
//window.frames.UIContentsImgFrameiFrame.location.href = srcURL + "#file";
//prepare link for full-size picture:
//cutURL = cutURL.replace('thumb/','');
//cutURL = cutURL.substring(0, cutURL.lastIndexOf('/'));
//show preview thumb version
//if (cutURL.match(/\.svg$/)) cutURL = srcURLFromWikiPage;
alert('img src: ' + cutURL);
//show preview thumb version
var elemImg = document.getElementById('UIContentsImgFrameImage');
document.getElementById('UIContentsImgFrame').style.display = 'block';
//set image source
if (showHigherResolution == true) elemImg.onload = 'UIContents.resizeImage()';
elemImg.alt = 'loading...';
elemImg.src = cutURL;
elemImg.style.visibility = 'hidden';
elemImg.style.visibility = 'visible';
imageViewIsOpened = true;
document.getElementById('UISearchField').style.visibility = 'hidden';
document.getElementById('UISearchTextInput').style.visibility = 'hidden';
Any suggestions? Thanks in advance.
var cutURL = srcURLFromWikiPage.replace("file://localhost/","http://");