How to change the image a source is associated with - javascript

Is there anyway that I can put an image on my site that changes.
I know how to change the source of an image element. What I mean is like:
the image is located here
http://mywebsite.com/image.png
this doesn't change but I want the actual image to change.
More examples:
https://huggle.jdf2.org/
This site creates a bbcode element that contains the img username.png
[url=http://huggle.jdf2.org/hug/username][img]http://huggle.jdf2.org/sig/username.png[/img][/url]
This image changes depending on how many huggles you have.
How would I do this?

You can dynamically set the image source URL with:
var yourURLHere = 'ADD YOUR URL HERE';
image.src = yourURLHere;
If you want the your image to randomly change, you can use Math.random() to select a random URL from an array.
Example: Random teddy bear images (see below).
<image src="#" id="my-image"/>
Click to change image randomly.
<button id="my-btn">Change it!</button>
<script>
var imageURLs = [
'https://s-media-cache-ak0.pinimg.com/originals/4e/da/9f/4eda9f56de08463bcc18d154f654ab6d.jpg',
'http://lcdn.inthelighturns.com/media/product/e85/sweet-memories-blue-teddy-bear-urn-b83.jpg',
'https://s-media-cache-ak0.pinimg.com/originals/3c/80/3c/3c803ce72e8c0325d7ea0fcd32f81ed9.jpg',
'http://cliparting.com/wp-content/uploads/2016/07/Cartoon-teddy-bear-clipart.gif',
'http://cliparts.co/cliparts/rcn/Kox/rcnKox65i.png',
'https://s-media-cache-ak0.pinimg.com/originals/f2/d6/25/f2d6258ef0fa6de2160778066ccec832.jpg',
'https://s-media-cache-ak0.pinimg.com/236x/90/3a/6c/903a6c59c0a2f42e7d6e7cb9427a8337.jpg',
'https://s-media-cache-ak0.pinimg.com/564x/a9/ee/30/a9ee30a4f8d196a111aa5c3db7b13b6e.jpg',
'http://cdn3.volusion.com/9nxdj.fchy5/v/vspfiles/photos/BB-1433-2.jpg?1415360799'
];
var image = document.getElementById('my-image');
function pickRandomURL() {
return imageURLs[Math.floor(Math.random() * imageURLs.length)];
}
image.src = pickRandomURL();
image.width = 200;
var btn = document.getElementById('my-btn');
btn.onclick = function() {
image.src = pickRandomURL();
image.width = 200;
};
</script>

Related

How to save canvas on Right-Click dialog as jpg

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!

Browser scroll bar shift after adding an image with javascript

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.

document.getElementById().src could not present images under Jquery template

I have a question of document.getElementById().src under jQuery Template.
Firstly I created an array of 5 pictures(only the first element was depicted) as showed below:
var Image = function(src){
this.src = src;
}
var images = [];
images[0] = new Image("images/hedgehog.jpg");
Then I created a function which includes passing the src of the array to an ID(only relevant code was depicted):
document.getElementById("theQ").src = images[0].src;
The final part is the place expected to present the picture, but it didn't work:
<p style="text-align:center;" id="theQ"></p>
The navigation is correct as I could see the picture when I hover on the URL in text editor. Thank you for the help!
A paragraph is not an image. You can't attach a source to it. And it makes no sense to shadow the image constructor, just use the native one:
const img = new Image();
img.src = "images/hedgehog.jpg";
Now you can easily append that image to the dom:
document.getElementById("theQ").appendChild(img);
Since you already use jQuery in your template.
var Image = function(src){
this.src = src;
}
var images = [];
images[0] = new Image("https://thumbs.dreamstime.com/b/woman-wearing-yellow-floral-top-116695890.jpg");
$("#theQ").append("<img src=\""+images[0].src+"\" width=\"150\" />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p style="text-align:center;" id="theQ"></p>

Is an event triggered when an HTML link element (<a/>) containing base64 data as href is ready?

I have created a webpage that basically displays 2 images side by side.
It has a "download" button, which triggers a vanilla Javascript function, which creates a <canvas> HTML element and concatenates the two images inside of it. It then creates a link with the base64-encoded result image as href and clicks on it:
<a download="image.png" id="dllink" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAAMnCAYAAABhnf9DAAAgAElEQVR4nOzdR48kD3rn96j03pfv6qo21dVd3qT3JryP9Jll281..."></a>
Here is what the function I'm using looks like:
/**
* Create canvas, draw both images in it, create a link with the result
* image in base64 in the "href" field, append the link to the document,
* and click on it
*/
function saveImage() {
// Get left image
var imgLeft = new Image();
imgLeft.setAttribute('crossOrigin', 'anonymous');
imgLeft.src = "imgleft/" + idxImageShownLeft + ".jpg";
imgLeft.onload = function() {
// Once the left image is ready, get right image
var imgRight = new Image()
imgRight.setAttribute('crossOrigin', 'anonymous');
imgRight.src = "imgright/" + idxImageShownRight + ".jpg";
imgRight.onload = function() {
// Once the right image is ready, create the canvas
var canv = document.createElement("canvas");
var widthLeft = parseInt(imgLeft.width);
var widthRight = parseInt(imgRight.width);
var width = widthLeft + widthRight;
var height = imgLeft.height;
canv.setAttribute("width", width);
canv.setAttribute("height", height);
canv.setAttribute("id", "myCanvas");
canv.setAttribute('crossOrigin', 'anonymous');
var ctx = canv.getContext("2d");
// Draw both images in canvas
ctx.drawImage(imgLeft, 0, 0);
ctx.drawImage(imgRight, widthLeft, 0);
// Create PNG image out of the canvas
var img = canv.toDataURL("image/png");
// Create link element
var aHref = document.createElement('a');
aHref.href = img;
aHref.setAttribute("id", "dllink");
aHref.download = "image.png";
// Append link to document
var renderDiv = document.getElementById("render");
renderDiv.replaceChild(aHref, document.getElementById("dllink"));
// Click on link
aHref.click();
}
}
}
My problem is that this works fine on Firefox, but not on Chrome.
After a bit of investigating, I realized that by setting a breakpoint before the aHref.click(); line in Chrome, it worked fine. I think that it means that the aHref.click(); is called before the <a href="data:image/png;base64,...></a> is ready to be clicked, but I don't know for sure.
I couldn't find a duplicate of this topic. What keywords should I use just to be 100% sure?
Am I investigating in the right direction?
Is there an event I could rely on in order to call aHref.click(); only when it is ready?
You could wrap it in an init function that gets called when the window completes loading.
function init() {
aHref.click();
}
window.onload = init;
Its similar to the vanilla equivalent of jQuery's .ready() method.
aHref , document.getElementById("dllink") appear to be same element ? Though "dllink" has not yet been appended to document when .replaceChild called ?
Try substituting
renderDiv.appendChild(aHref);
for
renderDiv.replaceChild(aHref, document.getElementById("dllink"));

How to use JavaScript to put image src into HTML?

I want to put image src into my code.
This is my JavaScript code so far:
<script>
function images(){
var randomizer = Math.floor((Math.random() * 5)
var pictures =["images1.jpg","images2","images3.jpg","images4.png","images5.jpg"]
}
</script>
and this is my HTML code:
<img id = "bubbles" src="images1.jpg" width="20%" alt = "pics">
<img id = "bubbles2" src="images2.jpg" width="20%" alt= "pics">
The problem that I am facing is that I am not able to put the arrayed string into the src.
The problem is that the src attribute of an image tag can't take in an array of images. You'll need a separate image tag for your photos.
var pictures = ["images1.jpg", "images2", "images3.jpg", "images4.png", "images5.jpg"];
for (var i = 0; i < pictures.length; i++) {
var imgEl = document.getElementById("bubbles");
imgEl.setAttribute("src", imEl[i]);
}
The above code will update the src attribute with the images in the array. However, this will probably so quick you'll only see the last one. You would need to figure out a timing mechanism or integrate your random number function to chose a random image.
Using Math.random()
var pictures = ["images1.jpg", "images2", "images3.jpg", "images4.png", "images5.jpg"];
var randomizer = Math.floor(Math.random() * 5);
var imgEl = document.getElementById("bubbles");
imgEl.setAttribute("src", imEl[randomizer]);

Categories