Adjust the size of an image and move its position both vertically and horizontally using Javascript

I am currently working on transforming an image both vertically and horizontally, as well as scaling it using JavaScript. While I have managed to resize the image successfully, it doesn't quite look how I want it to. I am aiming for a similar effect as shown in this example. When adjusting the vertical bar, the image should move up and down, and when adjusting the horizontal bar, the image should move left or right. The current "testresize()" function does resize the image, but it's not achieving the desired outcome. I would like to apply CSS transform properties such as translateX(), translateY(), and scale() transforms to each image individually. You can find a demo of what I'm describing here: Range Slider Demo.

<div id="toggle-components">
                    <fieldset>
                        <legend>Choose image to display</legend>
                        <input type="checkbox" id="mage1" onclick="if(this.checked){displayimg()}")><label for="image1">diving</label>
                        <input type="checkbox" id="mage2" onclick="if(this.checked){displaybgimage()}")><label for="image2">jumping</label>
                     
                </div>

<div id="container">
 <img id="dolphin1" class="image" src="../images/img/image1.png" >
            <img id="dolphin2" class="image" src="../images/img/image2.png" >
            
        </div>

<div id="adjust-components">
                    <fieldset>
                        <legend>Adjust image</legend>

                        <label for="vertical-control">move vertical:</label>
                        <input id="vertical-control" type="range" min="-100" max="100" value="0" ><br>

                        <label for="size-control">resizesize:</label>
                        <input id="size-control" type="range" min="-100" max="100" value="0" onChange="testresize(this.value)"><br>

                        <label for="horizontal-control">move horizontal:</label>
                        <input id="horizontal-control" type="range" min="-100" max="100" value="0" ><br>
                    </fieldset>
                </div>

var gettestimage=document.getElementsByClassName("image");
//resize image
function testresize(val){

    for(var i=0;i<gettestimage.length;i++){

        var chek1 = document.getElementById("image1");
        var chek2 = document.getElementById("image2");
      
        if(chek1.checked){
            gettestimage[0].style.width=5*(val / 1)+'px';
            console.log(val)

        }else if(chek2.checked){
            gettestimage[1].style.width=5*(val / 1)+'px';

        }

Answer №1

Why set the width and height to scale an image when you can simply use the transform css property? It's a straightforward solution - just swap out those width and height settings for the transform property instead. This method may initially only work with one image, but with some tweaking, it could easily be adapted to handle multiple images.

var image = document.getElementById("image1")

// The image transformation (scale, translation, rotation)
var transform = {
  translation: {
    x: 0,
    y: 0
  },
  scale: 1
};

function scaleImage(val){
  transform.scale = val;
  applyStyle()
}

function translateImage(axis, val){
  transform.translation[axis] = val;
  applyStyle()
}

function applyStyle() {
  image.style.transform = `scale(${transform.scale}) translate(${transform.translation.x}px, ${transform.translation.y}px)`
}
<div id="container">
  <img id="image1" class="image" src="https://www.w3schools.com/w3css/img_lights.jpg" width="500">
</div>
        
<div id="adjust-components">
  <fieldset>
    <legend>Adjust image</legend>
    <label for="vertical-control">move vertical:</label>
    <input id="vertical-control" type="range" min="-100" max="100" value="0" onchange="translateImage('y', this.value)"><br>
    <label for="size-control">scale:</label>
    <input id="size-control" type="range" min="0" max="2" value="1" step="0.1" onchange="scaleImage(this.value)"><br>
    <label for="horizontal-control">move horizontal:</label>
    <input id="horizontal-control" type="range" min="-100" max="100" value="0" onchange="translateImage('x', this.value)"><br>
  </fieldset>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switching CommonJS modules to an ESM syntax for better compatibility

I'm currently facing a challenge in grasping the process of importing CommonJS modules into an ESM syntax. Specifically, I am working with the library url-metadata. This library provides a top-level export as a callable function, which deviates from t ...

What could be the reason for box-shadows not appearing properly on Safari browsers?

Why are box shadows with decimals sometimes not displayed in Safari? Is there a solution to this issue? Here's an example of the code: div { width: 200px; height: 200px; box-shadow: 0px 0.0351725rem 0.0351725rem 0px, 0px 0px 0px 0.0175862re ...

Unexpected results: jQuery getJSON function failing to deliver a response

I am facing an issue with the following code snippet: $.getJSON('data.json', function (data) { console.log(data); }); The content of the data.json file is as follows: { "Sameer": { "Phone": "0123456789", }, "Mona": { "Phone": ...

Analyzing the functionality of Express with Mocha and Chai

Currently facing an issue with testing my express server where I am anticipating a 200 response. However, upon running the test, an error occurs: Test server status 1) server should return 200 0 passing (260ms) 1 failing 1) Test server statu ...

The Vue select change event is being triggered prematurely without any user interaction

I am facing an issue with my Vue app where the change event seems to trigger even before I make a selection. I tried using @input instead of @change, but encountered the same problem as described below. I have tested both @change and @input events, but th ...

To open a popup menu with a text box, simply click on the text box

Whenever the text box text is clicked, a popup menu should open with a text box. Similarly, when the filter icon in the right side corner is clicked, a menu should open with a list of checkboxes. However, currently both menus are opening when clicking on b ...

"Material-UI enhanced React date picker for a modern and user-friendly

Currently, I am utilizing the Date picker feature from Material UI. The code snippet responsible for implementing it is as follows: import { DatePicker } from 'redux-form-material-ui'; <Field name="birthDate" ...

What are the reasons behind the jQuery file upload failing to work after the initial upload?

I am currently utilizing the jQuery File Upload plugin. To achieve this, I have hidden the file input and set it to activate upon clicking a separate button. You can view an example of this setup on this fiddle. Here is the HTML code snippet: <div> ...

Fastblox - utilizing javascript SDK for group chatting

I've been facing issues setting up a group chat using QB Javascript SDK. There are a few problems I am encountering: Firstly, I consistently receive a "room is locked" message. Here's the link to the screenshot: https://i.sstatic.net/auR21.png. ...

Tips for creating a Google Chart using temperature and humidity data sourced from an XML file

Below is the XML file I am working with: <data> <temp>21</temp> <humidity>17</humidity> <analog>670</analog> <analog>908</analog> <analog>628</analog> <analog>909</analog> <L ...

In TypeScript, an interface property necessitates another property to be valid

In the scenario where foo is false, how can I designate keys: a, b, c, bar as having an undefined/null/optional type? Put simply, I require these properties to be classified as mandatory only when foo is true. interface ObjectType { foo: boolean; a: nu ...

What is the best way to ensure that my $.ajax POST call works seamlessly with SSL?

Below is the JavaScript code I am using: parameter = "name=" + name + "&email=" + email + "&phone=" + phone + "&comments=" + comments; $.ajax({ url: 'sendEmail.php?' + parameter, success: ...

What is the method for extracting a list of properties from an array of objects, excluding any items that contain a particular value?

I have an array of objects, and I want to retrieve a list with a specific property from those objects. However, the values in the list should only include objects that have another property set to a certain value. To clarify, consider the following example ...

Why does it appear that Angular is undefined in this straightforward Angular demonstration?

I'm completely new to AngularJS and I've encountered an issue. Yesterday, I ran a very simple AngularJS application that I downloaded from a tutorial and it worked perfectly. The application consists of 2 files: 1) index.htm: <!DOCTYPE htm ...

How can I prevent list items in jQuery Mobile from being truncated with ellipses?

Here is the list I am working with: <ul id="linksList" data-role="listview" data-inset="true" data-filter="true"> <!-- Dynamic contents! --> </ul> This list pulls its data from a local XML file (RSS feed). I am looking f ...

When the button onClick event is not functioning as expected in NextJS with TypeScript

After creating a login page with a button to sign in and hit an API, I encountered an issue where clicking the button does not trigger any action. I have checked the console log and no errors or responses are showing up. Could there be a mistake in my code ...

Encountering a "require is not defined" error when trying to launch a Selenium

I have developed a basic selenium application and now I am looking to implement a graphical user interface for it. Here is the code snippet: index.html: <html> <head> <meta charset="UTF-8" /> <title>Selenium Ap ...

Guide to embedding bootstrap.min.js into ember-bootstrap extension

I'm currently experiencing an issue with the ember-bootstrap plugin. Following the instructions on their setup page at , I downloaded and installed it. Once I began working on the Navbar, I encountered a problem. The Hamburger menu, which is supposed ...

What is the best way to incorporate polling into the code provided below? I specifically need to retrieve data from the given URL every 60 seconds. How should I go about achieving this

Can you assist me in integrating polling into the code below? <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="https://code.highcharts.com/highcharts.js"> ...

Organize items within a compartment using Bootstrap3

I have decided to update my website to Bootstrap3 and encountered a common issue that many others seem to be facing as well. I am trying to evenly distribute 4 elements, each approximately 220px wide, inside a 990px container. In the old version of Bootstr ...