Looking for assistance with resizing and repositioning an image within a viewport?

The JSFiddle code can be found at this link - https://jsfiddle.net/pmi2018/smewua0k/211/

Javascript

$('#rotate').click(function(e) {
  updateImage(90, 0)
  console.log("rotation");
});

$('#zoom-in').click(function() {
  updateImage(0, 0.1);
  console.log("Zoomed in");
});

$('#zoom-out').click(function() {
  updateImage(0, -0.1);
  console.log("Zoomed out");
});

var zoomLevel = 1;
var rotation = 0;

var updateImage = function(angle, zoom) {
  zoomLevel += zoom;
  var img_scale = ' scale(' + zoomLevel + ') ';

  rotation += angle;
  if (rotation == 360) {
    rotation = 0;
  }
  var str_rotation = ' rotate(' + rotation + 'deg) ';
  console.log("rotation=" + str_rotation + " scale=" + img_scale);
  var img = document.getElementById('sam');
  img.style.transform = img_scale + str_rotation
}

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<button type="button" id="zoom-in">zoom in</button> <button type="button" id="zoom-out">zoom out</button> 

<div id=imageblock>
  <img  id="sam" src="http://placekitten.com/g/250/250" />
</div>
<div>
  <a id="rotate" href="#">Rotate 90 degrees</a>
</div>

CSS

#imageblock {
  width: 300px;
  height: 300px;
  border: 1px solid #000000;
  overflow: auto;
  display: block;
}

#sam {
  transform-origin: center, center;
}

In order to keep the scaled image within the box, the origin must be set to upper left corner, and for rotating it has to be center, center. However, applying both rotation and scaling separately does not work as only the first transformation is applied.

How can I achieve both rotation and scaling of the image in the #imagebox?

Thank you!

Mark

Answer №1

When it comes to why certain transformations work well together, the key lies in understanding that the transform property can only have one origin. This means that if you apply multiple transformations to a single object, they will all share the same origin.

To address this issue, a simple solution is to place the image within a div element. From there, you can utilize zoom on the div and rotation on the image separately, allowing them to have different origins.

$('#rotate').click(function(e) {
  updateImage(90, 0)
});

$('#zoom-in').click(function() {
  updateImage(0, 0.1);
});

$('#zoom-out').click(function() {
  updateImage(0, -0.1);
});

var zoomLevel = 1;
var rotation = 0;

var updateImage = function(angle, zoom) {
  zoomLevel += zoom;
  var img_scale = ' scale(' + zoomLevel + ') ';

  rotation += angle;
  if (rotation == 360) {
    rotation = 0;
  }
  var str_rotation = ' rotate(' + rotation + 'deg) ';

  // Some modifications were made here, utilizing JQuery methods instead of pure JavaScript
  // The image's rotate property is updated first, followed by the div's scale property
  $('#sam').css('transform',str_rotation)
  $('#zoom').css('transform', img_scale);
}
#imageblock {
  width: 300px;
  height: 300px;
  border: 1px solid #000000;
  overflow: auto;
  display: block;
  overflow: hidden; /* To hide the scrollbar when you zoom in */
}

#zoom {
  transform:scale(1);
  transform-origin:top left;
}

#sam {
  transform: rotate(0deg)
  transform-origin: center center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<button type="button" id="zoom-in">zoom in</button> <button type="button" id="zoom-out">zoom out</button> 

<div id=imageblock>
  <div id="zoom"> <!-- I added this div -->
    <img  id="sam" src="http://placekitten.com/g/250/250" />
  </div>
</div>
<div>
  <a id="rotate" href="#">Rotate 90 degrees</a>
</div>

It's worth noting that there shouldn't be a comma in transform-origin: center center;.

If you have any questions, feel free to ask. Hopefully, this explanation has been helpful!

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

Utilizing AngularJS: Executing directives manually

As a newcomer to AngularJS, I am facing a challenge that requires creating a 3-step workflow: The initial step involves calling a web service that provides a list of strings like ["apple", "banana", "orange"]. Upon receiving this response, I must encap ...

Utilizing a JavaScript variable within a jQuery function as an attribute

var image = "path.png"; Is it possible to include the 'image' variable in the jQuery function like this? $('#mapfoto').prepend('<img id="theImg" src="http://path.gr/" + image />'); ...

show image with the help of jquery and ajax

To showcase company information along with an image, I have a controller set up as follows: public JsonResult DisplayCompanyDetails() { CompanyModel cm = new CompanyModel(); string query = "select CompanyName,Address,Conta ...

Displaying the active navigation element in ApyCom JavaScript jQuery menu: tips and tricks

Currently, I am utilizing the jQuery navigation menu from ApyCom. Everything seems to be functioning properly except for one issue. Whenever I click on a different navigation element, I expect that element to remain highlighted in order to indicate to the ...

Using jQuery to reference a specific div and the ID within that div

Is there a way to track when a link is clicked and reference an ID as a variable within the link? For example, if I have a link like this: <a class="TrackClick" id="SomeUnknownVar" href="javascript:void(0)" onClick="window.open('http://someurl&apo ...

Tips to prevent the webpage from scrolling to the top when clicking on an anchor with an ID

I have developed a CSS/HTML carousel that consists of 4 slides. The goal is to display the selected slide when clicking on the bottom button (a href). However, I am facing an issue where every time I click on a link, the selected slide appears as intended ...

"Unlock the secrets to commanding respect in the web form layout by mastering the art

I have a fieldset that includes a legend with potentially long text content. I need the legend to only take up 50% of the width of the fieldset. Currently, when the legend is too lengthy, it still occupies 50% of the space but causes the entire fieldset ...

Having trouble scaling image with CSS, not reacting to size properties

I have little experience in web development, but a small business client has me working on their website while I handle other tasks for them. I've created a home page design that is almost ready to be turned into a template for the chosen CMS. Things ...

Transfer razor javascript calls in Blazor WebAssembly to a separate class

Scenario Description Greetings, I am currently working on a Blazor WebAssembly project that involves JavaScript interop. Initially, I had this functionality working in a .razor page. However, I now intend to encapsulate and centralize these JavaScript inv ...

The contents of req.body resemble an empty {}

Does anyone know why the req.body is empty in this code snippet? Even though all form data is submitted, it doesn't seem to be recognized in the req.body. Strangely enough, it works perfectly fine in postman. Take a look at the server-side code: con ...

Optimal Placement of jQuery Event Handlers in React/Redux Components with Asynchronous Data Loading

After reviewing the ReactJS documentation, it's clear that the most suitable lifecycle method for handling redux action calls is componentDidMount. However, I'm facing a challenge when it comes to incorporating jQuery operations within this parti ...

The error "500 window is not defined in Nuxt3 when using the composition API"

Is it possible to detect the user's preference for color scheme and set a data-mode attribute on the document root (html)? I've been struggling with this. In my app.vue code, I have the following: <template> <div> <NuxtLayout /> ...

Implementing a Button Click Event Listener on a Separate Component in React

Currently, my React application incorporates MapBox in which the navbar is its parent component. Within the navbar component, there is a button that collapses the navbar when clicked by changing its CSS class. I also want to trigger the following code snip ...

The background color of the CSS div tag does not cover the entire axis

I'm facing a dilemma in my CSS design that's got me stuck. This issue also seems to be present in this forum: Whenever I zoom in on the page, I noticed that the header background doesn't fully extend across the screen horizontally. Here&apo ...

JavaScript ACTING UP -> CROSS-ORIGIN RESOURCE ACCESS ERROR

After extensive research and troubleshooting, it dawned on me that the issue was not with JavaScript itself. Instead, I was facing a cross origin resource exception, which occurred because the ajax request was unable to access my server script due to lac ...

Utilizing a Static Image Path Prop in React JS: A Step-by-Step Guide

My Main Component import React from "react"; import TopModal from "./components/topModal"; // Passing productImage to the Child Component import productImage from "../../../../../../assets/images/juices.jpg"; import { makeS ...

Is it possible to extract the selected indexes of all select menus in my HTML and assign them to various arrays of my choosing? I find myself writing a lot of code just for one select menu

In order to determine which TV character the user most closely resembles based on their answers to a series of questions, I have created a function. However, my current code is inefficient when it comes to handling multiple select menus! I am considering i ...

Looking for a solution to my issue - my for loop is looping more times than it should

I am designing a confirm dialog using jQuery and Bootstrap. When the user clicks on 'Yes' or 'No', it should trigger an action, such as drawing two squares each time. The first time I click either button, it draws 2 squares. However, wi ...

Calculating the sum of table columns with the help of knockout.js

Is there a way to calculate the table columns using knockout.js? I am familiar with jQuery but new to knockout.js and unsure how to approach this. Instead of generating the table data using JSON, I would like to directly create it in the HTML table itself. ...

Inquiries regarding real-time alerts and notifications

Just curious, I am wondering about the creation of those notifications/alerts (for example on platforms like twitchalerts, commonly used by livestreamers). Are they typically coded in JavaScript/AJAX or another language? Is there a specific framework for ...