<img>(screen.width, screen.height) [duplicate] - javascript

I'm trying to change the size of an image with JavaScript. The jS file is separate from the HTML page.
I want to set the height and width of an image in the JS file. Any good ways on doing this?

Once you have a reference to your image, you can set its height and width like so:
var yourImg = document.getElementById('yourImgId');
if(yourImg && yourImg.style) {
yourImg.style.height = '100px';
yourImg.style.width = '200px';
}
In the html, it would look like this:
<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>

You can change the actual width/height attributes like this:
var theImg = document.getElementById('theImgId');
theImg.height = 150;
theImg.width = 150;

If you want to resize an image after it is loaded, you can attach to the onload event of the <img> tag. Note that it may not be supported in all browsers (Microsoft's reference claims it is part of the HTML 4.0 spec, but the HTML 4.0 spec doesn't list the onload event for <img>).
The code below is tested and working in: IE 6, 7 & 8, Firefox 2, 3 & 3.5, Opera 9 & 10, Safari 3 & 4 and Google Chrome:
<img src="yourImage.jpg" border="0" height="real_height" width="real_width"
onload="resizeImg(this, 200, 100);">
<script type="text/javascript">
function resizeImg(img, height, width) {
img.height = height;
img.width = width;
}
</script>

Changing an image is easy, but how do you change it back to the original size after it has been changed? You may try this to change all images in a document back to the original size:
var i,L=document.images.length;
for(i=0;i<L;++i){
document.images[i].style.height = 'auto'; //setting CSS value
document.images[i].style.width = 'auto'; //setting CSS value
// document.images[i].height = ''; (don't need this, would be setting img.attribute)
// document.images[i].width = ''; (don't need this, would be setting img.attribute)
}

you can see the result here
In these simple block of code you can change the size of your image ,and make it bigger when the mouse enter over the image , and it will return to its original size when mouve leave.
html:
<div>
<img onmouseover="fifo()" onmouseleave="fifo()" src="your_image"
width="10%" id="f" >
</div>
js file:
var b=0;
function fifo() {
if(b==0){
document.getElementById("f").width = "300";
b=1;
}
else
{
document.getElementById("f").width = "100";
b=0;
}
}

Direct manipulation
HTML tag declaration for image:
<img id="my-img" src="src/to/your/image.jpg" width="1280px" height="720px" />
<!-- OR -->
<img id="my-img" src="src/to/your/image.jpg" style="width: 1280px; height: 720px;" />
Handling html tag by direct access to object image:
const myImg = document.getElementById("my-img");
// Set a new width and height
myImg.style.width = "800px";
myImg.style.height = "450px";
// Or set a new width and height by attribute
// This option is not advisable because the attribute has a
// low priority over the style property.
myImg.setAttribute("width", 800);
myImg.setAttribute("height", 450);
Functions for manipulation
Using the updateImageSizeWithWidth or updateImageSizeWithHeight method below, you can increase or decrease any image without having to explicitly specify the exact width and height, you only need one value out of these two to update the image size.
/**
* Update image size using width
*
* param {HTMLImageElement} img
* param {number} newWidth
*/function updateImageSizeWithWidth(img, newWidth) {
// Getting the width and height of the current image
const oldWidth = Number.parseFloat(getComputedStyle(img).width || img.getAttribute("width"));
const oldHeight = Number.parseFloat(getComputedStyle(img).height || img.getAttribute("height"));
// Getting proportional height with new width
const newHeight = (newWidth * oldHeight)/oldWidth;
// Setting dimensions in the image
img.style.width = `${newWidth}px`;
img.style.height = `${newHeight}px`;
}
/**
* Update image size using height
*
* param {HTMLImageElement} img
* param {number} newHeight
*/
function updateImageSizeWithHeight(img, newHeight) {
// Getting the width and height of the current image
const oldWidth = Number.parseFloat(getComputedStyle(img).width || img.getAttribute("width"));
const oldHeight = Number.parseFloat(getComputedStyle(img).height || img.getAttribute("height"));
// Getting proportional height with new width
const newWidth = (newHeight * oldWidth)/oldHeight;
// Setting dimensions in the image
img.style.width = `${newWidth}px`;
img.style.height = `${newHeight}px`;
}
updateImageSizeWithWidth(myImg, 800);
// Or
updateImageSizeWithHeight(myImg, 450);

// This one has print statement so you can see the result at every stage if you would like. They are not needed
function crop(image, width, height)
{
image.width = width;
image.height = height;
//print ("in function", image, image.getWidth(), image.getHeight());
return image;
}
var image = new SimpleImage("name of your image here");
//print ("original", image, image.getWidth(), image.getHeight());
//crop(image,200,300);
print ("final", image, image.getWidth(), image.getHeight());

You can do this:
.html file:
<img src="src/to/your/img.jpg" id="yourImgId"/>
.js file:
document.getElementById("yourImgId").style.height = "heightpx";
The same you can do with the width.

Related

How to detect if an image was clicked

I am trying to detect if an image was clicked. To give some context, I am making a cookie clicker game where if you click it 10 times, a new image will appear which will give double points. For the first image I used
document.querySelector('#clickme1').onclick=scooore;
Then I am adding new images with the following function:
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);
}
My problem is how do I add to my variable (scree) since it is local and the first way needs to use a whole diff function.
function scooore() {
scree = scree + 1;
document.getElementById("scorez").innerHTML = "Image has been clicked " + scree + " times";
Been working for 40+ mins on this probably 1 line of code solution and couldn't find a solution so turning to the nice people at stack overflow
In addition to the code I posted below, what will really help you as you continue to develop your project is if you have an array of data for each image (whether that is an object or another array).
// Put on outside so that image may change instead of clone
var img = document.createElement("img")
// Fill out initial image specs
img.src = src
img.width = width
img.height = height
img.alt = alt
function show_image(src, width, height, alt) {
img.src = src
img.width = width
img.height = height
img.alt = alt
}
var scree = 0
function scooore() {
scree++
document.getElementById("scorez").innerHTML = "Image has been clicked " + scree + " times"
// If score is divisible by 10
if (scree % 10 === 0) {
show_image(src, width, height, alt)
}
}
document.querySelector('#clickme1').onclick = scrooore()

Placing an image on a canvas JS

I have the following in html:
<img id="MarkingImage"></img>
<canvas id="MarkingCanvas"></canvas>
And on css:
#MarkingCanvas { width: 100%; background-color: #7986CB; height: 96%; }
#MarkingImage { position: absolute; }
And on js:
function LoadImage()
{
var markingImage = new Image();
markingImage.addEventListener('load', function()
{
m_imageWidth = this.naturalWidth;
m_imageHeight = this.naturalHeight;
m_markingCanvasContext.drawImage(markingImage, 0, 0, m_imageWidth, m_imageHeight);
});
markingImage.src = 'PICT0001.JPG';
}
The thing is that this output stretches the image and it's quality gets really poor (see attached "Original" and "Result").
When I debug, I can see that the sizes if my canvas are:
width - 1410
height - 775
The sizes if my image are:
width - 551
height - 335
So my question is: why isn't the image placed in it's original size? I mean, there's enough space on the canvas. Also, why does the image gets stretched, and as a result gets in pretty low quality. Appears like it stretches beyond the size of the canvas.
What am I missing here?
You need to set the canvas width and height dynamically according to the browser window's width and height. also, there is no need to use the image's naturalWidth / naturalHeight.
var m_markingCanvas = document.getElementById('MarkingCanvas');
var m_markingCanvasContext = m_markingCanvas.getContext('2d');
// setting canvas width and height dynamically
m_markingCanvas.width = window.innerWidth;
m_markingCanvas.height = window.innerHeight;
function LoadImage() {
var markingImage = new Image();
markingImage.addEventListener('load', function() {
m_markingCanvasContext.drawImage(this, 0, 0);
});
markingImage.src = 'https://i.stack.imgur.com/a3Wpy.jpg';
}
LoadImage();
<canvas id="MarkingCanvas"></canvas>

Change Image() object dimensions (width and height)

I am attempting to resize an image's dimensions, whilst retaining it's aspect ratio. This seems like a very simple task, but I cannot find a rellevent answer anywhere.. (relating to JavaScript's Image() object). I'm probably missing something very obvious. Below is what I am trying to achieve:
var img = new window.Image();
img.src = imageDataUrl;
img.onload = function(){
if (img.width > 200){
img.width = 200;
img.height = (img.height*img.width)/img.width;
}
if (img.height > 200){
img.height = 200;
img.width = (img.width*img.height)/img.height;
}
};
This is to proportionally resize an image before being drawn onto a canvas like so: context.drawImage(img,0,0,canvas.width,canvas.height);.However it would appear I cannot directly change Image()dimensions, so how is it done? Thanks.
Edit: I haven't correctly solved the image proportions using cross-multiplication. #markE provides a neat method of obtaining the correct ratio. Below is my new (working) implementation:
var scale = Math.min((200/img.width),(200/img.height));
img.width = img.width*scale;
img.height = img.height*scale;
clearCanvas(); //clear canvas
context.drawImage(img,0,0,img.width,img.height);
Here's how to scale your image proportionally:
function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
return(Math.min((maxW/imgW),(maxH/imgH)));
}
Usage:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/balloon.png";
function start(){
canvas.width=100;
canvas.height=100;
var w=img.width;
var h=img.height;
// resize img to fit in the canvas
// You can alternately request img to fit into any specified width/height
var sizer=scalePreserveAspectRatio(w,h,canvas.width,canvas.height);
ctx.drawImage(img,0,0,w,h,0,0,w*sizer,h*sizer);
}
function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
return(Math.min((maxW/imgW),(maxH/imgH)));
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<h4>Original Balloon image resized to fit in 100x100 canvas</h4>
<canvas id="canvas" width=100 height=100></canvas>
The image dimensions are set in the constructor
new Image(width, height)
// for proportionally consistent resizing use new Image(width, "auto")
or
the context.drawImage()
the arguments are as follows:
context.drawImage(image source, x-coordinate of upper left portion of image,
y-coordinate of upper left portion of image,image width,image height);
simply position the the image with the first two numeric coordinates and then manually adjust the size with the last two (width,height)
//ex.
var x = 0;
var y = 0;
var img = new Image (200, "auto");
img.src = "xxx.png";
context.drawImage(img,x,y,img.width,img.height);

Javascript Image() object erroneously setting height and width to 0 sometimes

I'm working on an app that is dynamically generating images with Javascript's image() object. Code below, where object is the URL I am passing in -
resizeImage: function(object) {
var img = new Image();
img.src = object;
console.log(img);
console.log(img.width);
console.log(img.height);
var ratio;
if(img.width > img.height) {
ratio = 82/img.width;
} else {
ratio = 82/img.height;
}
img.height *= ratio;
img.width *= ratio;
return img;
},
The output of my console log shows the image object is created with source set to URL -
<img src="https://z3nburmaglot.zendesk.com/attachments/token/F0Y7C9UfUcOaA7nCMJfE5T1yB/?name=Show+Support+Tickets+on+Customer+View.png"> and height and width of 0.
Some of the images load fine - they set height and widgth appropriately and if I refresh the JS (run the function again), the images that had 0 height and width suddenly change to the correct height and width.
Any thoughts on why constructing an image this way would fail sometimes?
Sounds like your image hasn't loaded yet when you get its width or height. Then it will be 0.
When you refresh, the image is in your browser cache and will load immediately so its width and height are available straight up.
Use the onload() event of the Image object to execute code once the image has been loaded properly
resizeImage: function(object) {
var img = new Image();
// first set onload event
img.onload = function() {
console.log(img);
console.log(img.width);
console.log(img.height);
var ratio;
if(img.width > img.height) {
ratio = 82/img.width;
} else {
ratio = 82/img.height;
}
img.height *= ratio;
img.width *= ratio;
}
// then set the src
img.src = object;
return img;
},

Replace an existing element

if (yardss > 0.1 && yardss < 0.3) {
var img = document.createElement("img");
img.src = "images/wrench1.jpg";
img.align = "center";
document.body.appendChild(img);
} else if (yardss > 0.3) {
var img = document.createElement("img");
img.src = "images/wrench.jpg";
img.width = 500;
img.height = 300;
document.body.appendChild(img);
}
This script is activated by the user clicking on a button, and it prompts the user to enter a certain number of yards. If the yards are above a certain number, it displays a certain sized wrench. If it is below a certain number, it displays a different sized wrench.
My problem is that because the script can be run over and over again by clicking on the button, every time that the script is run, a new image of a wrench is produced below the previous image, creating a really long web page with a lot of images.
How do I make the newly created image replace the image created from the previous running of the script, instead of having the page fill with images from the script being run multiple times?
Use replaceChild instead of appendChild.
You can just change the .src property on the current image. There is no need to create a whole new image:
// get the current image object
// assumes you set id="wrenchImg" on it
var img = document.getElementById("wrenchImg");
if (yardss > 0.1 && yardss < 0.3) {
img.src = "images/wrench1.jpg";
img.height = ... // set this to whatever you need it to be for this image
img.width = ... // set this to whatever you need it to be for this image
img.align = "center";
} else if (yardss > 0.3) {
img.src = "images/wrench.jpg";
img.height = 300;
img.width = 500;
img.align = "left";
}
If you have any other properties of the image that must also be changed (height or width or alignment, for example), then you can add those to each branch of the if/else, but doing it this way, you have to fully initialize the image object because it may have been set a different way based on the previous image.
Don't create the img element again and again. Just create once and set some id on it. Then just change the src and width, height etc..
In HTML:
<img id= "wrench_img"/> // Setting id as wrench_img
In JavaScript:
function changer(yardss) {
var img1 = document.getElementById("wrench_img"); // Get the img
if (yardss > 0.1 && yardss < 0.3) {
img1.src = "images/wrench1.jpg"; // Change the src
img1.align = "center";
} else if (yardss > 0.3) {
img1.src = "images/wrench.jpg"; // Change the src
img1.width = 500; // Change width
img1.height = 300;
}
}
In your code, you were appending new image elements to the document.body. That is why you were getting multiple image elements. But if you look at this code, we don't create the image elements multiple times. We just change the one created.
Online Demo

Categories