How to display image with JavaScript? - javascript

I am trying to display image, through JavaScript, but i can't figure out how to do that. I have following
function image(a,b,c)
{
this.link=a;
this.alt=b;
this.thumb=c;
}
function show_image()
{
document.write("img src="+this.link+">");
}
image1=new image("img/img1.jpg","dsfdsfdsfds","thumb/img3");
in HTML
<p><input type="button" value="Vytvor" onclick="show_image()" > </p>
I can't figure out where should I put something like image1.show_image();.
HTML? Or somewhere else...

You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

Thank you... I made small modifications/simplifications. Works as intended.
HTML:
Add Image
Javascript:
function addLogo() {
var src = "https://i.gifer.com/origin/93/935d72c7bc35828ea93b5898691f28fd_w200.gif";
show_image(src, 124,124, "My Image");
}
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}

Related

Set height of Img via JavaScript

I am currently running into a problem with my code. I am attempting to set the height of an image through JavaScript in a check that its less than 600 pixels. I have tried a plethora of alternatives to the general "this.height = 600" but none have resulted successfully. I am really hoping someone can help me fix this problem.
<div id="cursedframe">
<img src="" id="cursedimg">
</div>
<script>
function setImage() {
var img = new Image();
var images = [
"bean.jpg",
"xxx-edit-parallax/Images/xxx-5.jpg"
];
var chosen = images[Math.floor(Math.random() * images.length)];
img.onload = function(){
if (this.height > 600) {
console.log("more than");
this.height = 600;
console.log(img.height);
} else {
console.log("less than");
this.height = "auto";
console.log(this.height);
}
};
img.src = chosen.toString();
document.getElementById("cursedimg").src = img.src;
}
</script>
It successfully passes the "if" but never actually sets the height.
EDIT: Unaware of the CSS property of max-height and max-width at the time. Was brought to my attention by Lain. Thank you
It would be much easier to use the css property max-height.
Just to show the actual flaw with the approach in javascript: you have to pass the height on to the actual image. Currently you merely set it to the img object yet never to the shown image <img src="" id="cursedimg">.
var img = new Image();
var images = ['https://logosmarken.com/wp-content/uploads/2018/05/Google-Logo.png'];
var maxHeight = 200; //REM: For my test image
img.onload = function(){
if (this.height > maxHeight) {
console.log("more than");
this.height = maxHeight;
console.log(img.height);
} else {
console.log("less than");
this.height = "auto";
console.log(this.height);
};
//REM: Here you need to assign the src along with the height
document.getElementById("cursedimg").src = this.src;
document.getElementById("cursedimg").style.height = this.height + 'px';
};
//REM: No need for toString() - it already is.
img.src = images[Math.floor(Math.random() * images.length)];
<div id="cursedframe">
<img src="" id="cursedimg">
</div>
Even easier would be to not create a new object at all and just assign it as is:
var img = document.getElementById("cursedimg");
By running the following code, you are assigning the only the src attribute to the img element
img.src = chosen.toString();
document.getElementById("cursedimg").src = img.src;
If you want to set the height and src of the image element using javascript,
you can do the following:
var image = document.getElementById("cursedimg");
if ( image.height > 600 ){
image.height = 600;
}
else{
image.style.height = "auto"; // since 'auto' is a styling value
}
image.src = chosen.toString();

Images & PDFMake

I'm currently using pdfmake to generate project report pdf's given information, and I'm having some trouble getting images to display.
I have a function that generates a pdfmake "object" that goes like this:
function singleProject(data) {
return {
text: "Project: \n" + data.title + \n\nImage: \n",
pageBreak: 'before'
}
}
I want to add an image to that report given an image URL (something like "images/sample_image.jpg"), and from what I've read on other answers I have to convert it to a base 64 format.
One of these functions was provided in another answer but I can't quite figure out how I'm supposed to be utilizing it:
function convertImgToBase64URL(url, callback, outputFormat){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
var dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
However, I'm not exactly too sure how I should go about using this function to add the image to the first function provided, as it doesn't return the dataURL; if I try something like:
function singleProject(data) {
return {
text: "Project: \n" + data.title + \n\nImage: \n",
image: convertImgToBase64URL(data.image), //data.image is the URL so something like "images/sample_image.jpg"
width: 300,
pageBreak: 'before'
}
}
The image doesn't show up.
Use hidden
<img id='imgToExport' src='someimageurl' style='display:none'/>
and in JavaScript use
var imgToExport = document.getElementById('imgToExport');
var canvas = document.createElement('canvas');
canvas.width = imgToExport.width;
canvas.height = imgToExport.height;
canvas.getContext('2d').drawImage(imgToExport, 0, 0);
canvas.toDataURL('image/png')
By this way you donot need asynchronous call

How to resize the image before base64 conversion

In my sencha based application i want to convert the image into base64,Before that i want to resize the original one.Here the code which i have used to convert base64
function getBase64FromImageUrl(URL)
{
var img = new Image();
img.style.width = '5%',
img.style.height = '5%',
img.src = URL;
img.onload = function ()
{
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 10, 10);
var dataURL = canvas.toDataURL("image/jpg");
if(App.gvars.userpic=='1')
{
cdd=dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
if(App.gvars.userpic=='2')
{
c=dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
}
}
How to resize or redimension the image before conversion?I have tried with changing img.style.width and hieght but there is no change at all.Please help me
Per devnull69's suggestion, simply use drawImage() to resize the image when you add it into the canvas.
See the API at either W3Schools or MSDN.
You can even play with the values in a live-coding example at Html5CanvasTutorials

How to display an image as a property in JavaScript objects

//construtor created
function Blog(text, date, image) {
this.show_image = function(src, width, height, alt){
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
}
//instance
var blog = [new Blog("hello!,Welcome to my blog1.", new Date("10/21/2012"),'show_image("images/overlay.png", 20,30, "Google Logo")'),
Hey m calling an image in above instance for that i've written a function show_image performs that part but the image is not getting displayed...please tell me what is wrong here ...please modify it...I'm new in javascript programming..
I
i have no idea why are you creating constructor and all..this can be done, with creating a simple function
try this
function show_image(src, width, height, alt){
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
$(document).ready(function(){ //if using jquery
show_image("images/overlay.png", 20,30, "Google Logo");
});
You are actually not calling the show_images function. You are just passing a string and that is not going to help.
Remember before finding out why the particular block of code is not working, you need to find out if that block is executed at all.
This is one more way you make it work.
function Blog(text, date) {
this.show_image = function (src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
}
//instance
var blog = new Blog("hello!,Welcome to my blog1.", new Date("10/21/2012"));
blog.show_image("images/overlay.png", 20,30, "Google Logo");

jQuery: how to get the dimensions of a external image?

Looking for a way to get the dimensions (width and height) of an external image. I have used prop() and attr(), but they don't return any values. Just an error.
Example:
some link
jQuery
var path = 'https://source.unsplash.com/random/600x300/?montreal';
$("<img/>").attr('src', path).load(function() {
console.log(this.width, this.height);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Vanilla Javascript
var path = 'https://source.unsplash.com/random/600x300/?montreal';
var img = new Image();
img.src = path;
img.addEventListener('load', function() {
console.log(this.width, this.height);
});
Looks like none has provided a working vanilla js answer.
var img = document.createElement('img')
img.src = 'http://domain.com/img.png'
img.onload = function() {
console.log( this.width )
console.log( this.height )
}
Here is a jsfiddle: http://jsfiddle.net/Ralt/VMfVZ/
This isn't technically jQuery but I would go down the route of:
var image = new Image(), width, height;
image.src = 'http://whereyourimage.is/heresmyimage.jpg';
width = image.width;
height = image.height;
You can then access those values using width and height, for example alert('My image is ' + width + ' pixels accross.');

Categories

Resources