Guide to saving a rotated image in the local downloads directory with JavaScript

How can I save a rotated image using JavaScript or jQuery after rotating it by clicking on a rotate button? The code provided below shows the functionality for rotating an image and saving the rotated version. Feel free to provide your solution.

Code for rotating the image:


var angle = 0,
  img = document.getElementById('id');
document.getElementById('rotatedown').onclick = function() {
  angle = (angle + 270) % 360;
  img.className = "rotate" + angle;
  imgRotate = document.getElementById('id').src;
  $('.saverotatedown').css('display', 'block')
  $('.saverotateright').css('display', 'none')
  $('.saverotateup').css('display', 'none')
  $('.saverotateleft').css('display', 'none')
  let save = document.querySelector(".saverotatedown")
  save.addEventListener('click', () => {
    let a = document.createElement('a');
    a.href = imgRotate;
    a.download = 'imaged.png';
    document.body.appendChild(a);
    a.click();
  });
  console.log(img.className, imgRotate);
}
<title>Image upload</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="https://skillrary.com/uploads/images/fav-sr-64x64-logo.png" type="image/x-icon">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" crossorigin="anonymous" rel="preconnect" defer/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<img src="https://skillrary.com/uploads/images/f-sr-logo-195-50.png" id="id" /> 
<button id="rotatedown" class="rotateImgDiv"><i class="fa fa-undo" aria-hidden="true"></i> 
Rotate</button> 
<button class="btn saverotatedown" style="display: none">Save down</button>

Answer №1

The specified image link is

https://skillrary.com/uploads/images/f-sr-logo-195-50.png
. However, when a user attempts to save the edited image via their browser, it still calls for the original image.

Instead of directly manipulating the element using CSS, consider creating a new Image object in JavaScript and manipulating that to display on a canvas element. This way, the manipulated image can be downloaded in its altered state.

To implement this technique, add the following code snippet to your HTML:

<div id="canvas"></div>

Then, in your JavaScript script:

var img = new Image(); // Create a new image

// Set up a canvas element to serve as the area where your manipulated image will be displayed.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

// Specify the source of the Image Object.
img.src = 'https://skillrary.com/uploads/images/f-sr-logo-195-50.png';

// Perform your desired image manipulations here and finalize with drawImage();
ctx.drawImage(img, 0, 0);

For further guidance, refer to this resource.

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

Is it possible to modify the CSS produced by Bootstrap in an Angular application?

Just starting out with Angular and Bootstrap I have the following displayed in my browser: Browser Code shown through inspect and this is what I have in my code: <ng-template #newSlaVmData let-modal> <div class="modal-header moda ...

Ways to update the content of a NodeList

When I execute this code in the console: document.querySelectorAll("a.pointer[title='Average']") It fetches a collection of Averages, each with displayed text on the page: <a class="pointer" title="Average" onclick="showScoretab(this)"> ...

Renew the php blade foreach loop using jQuery to update data live

I have a foreach cycle in my HTML, and at one point, some data is posted from JavaScript. I would like to append it once it is added to the database. I need to find a way to refresh the foreach loop without reloading the entire page (I could simply use ap ...

Storing JSON Web Tokens (JWT) securely in Vuex state with the Nuxt Auth

While the login/logout/middleware functionalities are working, I am facing an issue with controlling the token. I am attempting to store the JWT in Vuex store after logging in, but it is only being saved in a cookie and localStorage. As per the documentati ...

How can I implement a CSS property on a child class when the parent class is toggled on and off?

Looking to style a child div within a parent div that toggles classes based on a flag. The parent div can have either the .pricing-section or .new-pricing-section class. Here's the structure of the parent div: const togglePriceSection = isPricingDetai ...

Creating a dynamic d3 force layout with interactive features in an Angular environment

I am currently working on a website using Angular and D3, although I don't have much experience with either of them. My goal is to create a force layout that is interactive, allowing users to select nodes and display related information in a sidebar. ...

Implementing raw static HTML files in webpack: a step-by-step guide

Recently, I created a basic template called test.html <div>raw text with content</div> All I'm trying to achieve is to import the raw file without any alterations For example: require('./test.html'); // This should return "&l ...

"Two columns of identical width, each occupying 50% of the screen height

I am currently working on a design featuring two columns, each set to occupy 50% of the width. I am facing a challenge with ensuring that the height of these columns stretches to the full height of the screen, even when they are empty, so I can showcase th ...

Creating an interactive map using Python with Folium, incorporating a draggable legend and clickable items for users to easily zoom into specific locations

Looking to create an interactive map with python folium package. Need icons for locations and a draggable legend that allows for repositioning by mouse drag. Also need ability to click on legend items to zoom into corresponding locations on the map. Can s ...

Uncovering the Mystery of AJAX and JSON in jQuery and NodeJS

Currently, I'm facing a challenge with an ajax function that sends a json to a nodejs route. I need to extract the selected values from 4 button-groups named quality, costeffectiveness, deliveryscope, and rating. Each button-group consists of 5 radio- ...

Is the issue of res.locals not being properly propagated to all requests in Express middleware persisting?

Currently, I am building a web app using express, node, and handlebars with passport as the authentication library. In an attempt to customize the navigation bar based on the user's state, I am trying to set a variable in res.locals. However, I am enc ...

How to add a gradient background in the most recent version of chart.js?

I came across a question about implementing gradients with the latest version of chart.js. I attempted to replicate it in this demo, but the gradient settings seemed to be ineffective. Do you have any suggestions on how to make it work? Below is the comp ...

JavaScript Pagination and JSON Concerns in Coding Techniques

Currently, I am pre-caching a dataset with a maximum limit of 500. The Ajax request fetches all the data at once, allowing for front loading and pagination. Everything works fine this way. However, we are in the process of transitioning our backend archit ...

A way to insert a line break in an HTML document without using the <br> tag is

<div id="unique_1" class="unique" style={{display:"flex"}} > <div class="item1">11</div> <div class="item2">77</div> <div class="item3">22</div&g ...

Activate or deactivate a radio button based on the selection of a specific date from the radio button

My goal is to create a functionality where radio buttons are enabled or disabled based on the selection of another radio button. Essentially, when a user clicks on a specific date radio button, the corresponding time slots for that date should be enabled. ...

The function Router.use is looking for a middleware function, but instead received an object in node.js /

I encountered an issue while trying to setup routing in my application. Whenever I attempt to initialize a route using app.use() from my routes directory, I receive an error stating that Router.use() requires a middleware function but received an Object in ...

Creating interactive forms that dynamically change based on the selected value in a dropdown menu

Looking to dynamically generate a form based on the selected value from a dropdown menu? Let's say we have a parent select box: <select name="select1" id="select1"> <option value="1">Fruit</option> <option value="2">Anima ...

Setting the [required] attribute dynamically on mat-select in Angular 6

I'm working on an Angular v6 app where I need to display a drop-down and make it required based on a boolean value that is set by a checkbox. Here's a snippet of the template code (initially, includeModelVersion is set to false): <mat-checkbo ...

The integration between Javascript, PHP, and SQL Server does not display the retrieved data

I am a beginner in PHP and have limited knowledge of Javascript. I am attempting to create a chronometer where the time limit is retrieved from a SQL SERVER database. However, when I assign the value obtained in PHP to a Javascript variable, it returns -1. ...

Conceal the frontview-specific attribute if the custom attribute value is empty

One of my recent projects involved creating a custom attribute value to display an external link on the product view. I used a custom attribute as a button that connected to my public marketplace store, such as Lazada. However, I encountered an issue when ...