Trim and Rotate Image

I'm currently working on a project to develop a feature on a website that crops an image to show only a portion of it while spinning.

The image consists of arrows pointing in various directions and I want it to rotate smoothly.

Answer №1

Presented here is a straightforward code snippet specifically for resizing images on the client side.

function resizeAndUpload(file) {
var reader = new FileReader();
    reader.onloadend = function() {

    var tempImg = new Image();
    tempImg.src = reader.result;
    tempImg.onload = function() {

        var MAX_WIDTH = 400;
        var MAX_HEIGHT = 300;
        var tempW = tempImg.width;
        var tempH = tempImg.height;
        if (tempW > tempH) {
            if (tempW > MAX_WIDTH) {
               tempH *= MAX_WIDTH / tempW;
               tempW = MAX_WIDTH;
            }
        } else {
            if (tempH > MAX_HEIGHT) {
               tempW *= MAX_HEIGHT / tempH;
               tempH = MAX_HEIGHT;
            }
        }

        var canvas = document.createElement('canvas');
        canvas.width = tempW;
        canvas.height = tempH;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0, tempW, tempH);
        var dataURL = canvas.toDataURL("image/jpeg");

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(ev){
            document.getElementById('filesInfo').innerHTML = 'Done!';
        };

        xhr.open('POST', 'uploadResized.php', true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        var data = 'image=' + dataURL;
        xhr.send(data);
      }

   }
   reader.readAsDataURL(file);
}

Source -

For more advanced options, consider utilizing pre-existing jQuery image plugins.

Source -

Answer №2

To contain the image within a smaller area, you can create a div with CSS overflow:hidden property. Take a look at this demonstration: http://jsfiddle.net/Nillervision/CBsLj/3/

#parentDiv{
    width:200px;
    height:200px;
    border:1px solid black;
    overflow:hidden;    
}
#theImage{
    margin-top:-100px;
    margin-left:-100px;
    width:400px;
    height:400px;
    display:block;
    -webkit-animation: rotAnim linear 5s infinite; 
    animation: rotAnim linear 5s infinite;
}
@-webkit-keyframes rotAnim { 
    from {
    -webkit-transform: rotate(0deg);
    }
    to {
    -webkit-transform: rotate(360deg);
    }

} 
@keyframes rotAnim { 
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }

}

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

How can you connect a jQuery UI sortable component to an array?

Is there a way to connect a jQuery UI sortable element with an array in order to assign an index to each sortable element within the array? I am looking for a method to automatically sort the array based on the movement of the sortable elements. Any sugg ...

transmitting JSON information and retrieving it again

I am currently navigating the process of passing objects through AJAX, and I find myself struggling with debugging as I am uncertain about both the passing and retrieving aspects. Essentially, my dilemma lies in making an AJAX request to a PHP controller ...

Update the WooCommerce shopping cart page automatically upon product removal

After trying to solve the issue of refreshing the cart page in WooCommerce when a product is removed, I came across this helpful question on Stack Overflow: Refresh the page after product remove from cart Woocommerce. Following the provided code snippet th ...

Is the order of execution of extraReducers before or after the reducers?

I was curious about the createSlice function in redux-toolkit and how it handles the order of execution for extraReducers compared to reducers. Can we determine if the extraReducers are executed before or after the reducers, or is the order indeterminate? ...

Setting up a dropdown list with a Django variable following an AJAX request

I am facing an issue with implementing a dropdown that triggers an AJAX call when a new value is selected. In my setup, the AJAX script calls a Django view which returns a list of values. The problem arises when I try to populate a second dropdown with the ...

What is the best way to choose and deselect a checkbox in Angular?

I'm currently working on an angular Todo list project where I'm tackling the challenge of implementing a select all and unselect all checkbox feature. todo.ts import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core&ap ...

Troubleshooting: Header Appears Slightly Below the Top of the Screen in CSS/HTML

Despite setting padding: 0; and margin: 0;, the div always appears below the top of the browser, without touching it. Below is the snippet of code: html, body { margin: 0; padding: 0; } .nav>ul>li { display: inline-block; padding: 0px 25 ...

Height and Width Dilemma in Visuals

Can you help with changing image resolution using jQuery? I have a background image applied to the body using CSS/PHP. My goal is to make the image fill the entire window by applying the screen height and width, without using repeat style. The code I am c ...

Guide to configuring a robust schema and validation with joi

Currently in the process of setting up validation using the joi package, encountering syntax-related issues along the way. The schema in place is simple, checking for a valid number and verifying if the ID exists in the database. export default router.pos ...

Curved Edges CSSPIE with a Touch of CSS Gradient

We are facing an issue with the code below, which creates a basic box with rounded corners and a gradient. We have applied CSSPie to achieve this effect, but we have observed that in all versions of Internet Explorer, the rounded corners do not work due to ...

Attempt to apply border-bottom style results in negligible changes

I have a snippet of HTML that showcases a grid-like structure. It's mostly how I want it to be, but I would like the last three rows to have a dotted underline. I attempted to achieve this using the following styling: style="border-bottom:dotted; bor ...

What steps should I take to ensure that the navbar is responsive and mobile-friendly?

After creating a navigation bar in an ejs file, I included it in all the files. The issue is that it looks fine on desktop view but does not respond well on mobile devices. There is some space left on the screen and it's not utilizing the entire width ...

Securing pathways and pages using NextJs

I recently completed a project where I implemented route protection for a website using the if and else statements, assigning each page a function withAuth(). However, I have concerns about whether this is the most effective method for securing routes in n ...

"Exploring the intricacies of jQuery's timing and cycling

I'm looking to create a brief newsflash feature on my website that will cycle through some text elements by fading them in and out... Here's what I have so far: $('.text01').hide().fadeIn('slow').delay(3000).fadeOut('sl ...

What is the best way to rearrange (exchange) elements within an Immutable Map?

Is there a way to rearrange items within an unchangeable list that is part of a Map? Here's an example: const Map = Immutable.fromJS({ name:'lolo', ids:[3,4,5] }); I have attempted to use the splice method for swapping, as well as ...

Obtaining the access token from the URL: A step-by-step guide

Once I have successfully authenticated with Google, the URL I receive is: http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600 I am tryi ...

Reaching out to the Edge: Enhancing the jQuery Slider Experience

Alright, I'm really excited about using this amazing slider. What I love most is the "free mode" feature that creates this stunning sliding effect. The size and number of slides are absolutely perfect for me. But there's just one small adjustment ...

What could be causing the issue with Google Chart in my ASP MVC app?

My controller has a method that returns Json data. [HttpPost] public JsonResult CompanyChart() { var data = db.adusers; var selectUsers = from s in data where (s.Company != null) select s; int f ...

Efforts to seamlessly combine two divisions of a business card through the use of CSS and HTML

Currently, I am working on designing a business card that includes both front and back sections. Below is the code snippet that I have been using: .business-card:hover .front{ transform: perspective(700px) rotateX(180deg); } .business-card .back{ tr ...

Utilize HTML strings to serve static files in express.js

While I primarily focus on frontend development, I often face challenges when working on the server side. Currently, I have a server.js file that includes: const express = require('express'); const http = require('http'); const path = ...