Non-Communication image rotation

Source: Internet
Author: User
Document directory
  • References:

Image rotation is a common operation in Web applications. When I was doing such a program, I had a narrow idea and always thought it was safer to throw it to the server. The general process of this method is as follows: when a user clicks a rotation direction, an Ajax request is sent immediately to tell the backend to rotate the image and the rotation angle, then, the backend generates new images using certain tools (such as the GD library of PHP), stores them, and returns the new image address to the browser, then, use JavaScript to update the src attribute of the image. This process is very simple for the front end. It is like the following:

$.ajax({url : 'url.php',type : 'GET',data : {degree : 90,imageId : id},success : function(src){image.src = src;}});

Although each angle image address that has been rotated can be cached on the front end, an Ajax request is still required when the image address is rotated to a new angle. You need a waiting process, the server also needs to process and store images, and it is very troublesome to delete these "process" images only when appropriate. In fact, canvas can be used to easily implement this function. for IE that does not support canvas, you can use a filter to achieve the same purpose. For this operation, IE filters are even simpler than canvas filters. Most importantly, because it is a pure front-end behavior, users can see the effect almost without waiting, and no HTTP requests are established, which will not affect the server.

Next we will implement the image rotation step by step in the pure front-end mode. The first is ie. in IE, the rotate attribute value of the basicimage filter is used to set the image rotation angle. According to Microsoft's documentation, this value can only be set to 0, 1, 2, 3, respectively, indicating the rotation of 0 degrees, 90 degrees, 180 degrees and 270 degrees, assuming that the image object is image and the rotation angle is degree, the specific code is very simple:

image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+degree/90+')';

The situations in other browsers are a little more complex. You need to use canvas to rotate the canvas using its rotate method and use its drawimage method to draw images on the canvas. The rotate method is very simple. It accepts a parameter, that is, the number of radians of rotation. Note that it is a radian rather than an angle. If you still remember high school mathematics, the conversion formula between radians and angles should be no stranger:

VaR radian = degree * Math. PI/180;/** radian = angle * π/180 **/

The drawimage method has many parameters, but here we use the first three parameters: image object, X coordinate of the starting point, and Y coordinate of the starting point. Before calling these methods, we need to append a canvas for the IMG element:

<canvas id="image_canvas"></canvas>

The following two elements are obtained in Javascript, and then the image and canvas are processed from different angles using the two methods just introduced:

var image = document.getElementById("rotate_demo");var canvas = document.getElementById("image_canvas");var ctx = canvas.getContext('2d');var width = image.width, height = image.height, x = 0, y = 0;switch(degree){     case 90:          width = image.height;          height = image.width;          y = image.height * (-1);          break;     case 180:          x = image.width * (-1);          y = image.height * (-1);          break;     case 270:          width = image.height;          height = image.width;          x = image.width * (-1);          break;}canvas.setAttribute('width', width);canvas.setAttribute('height', height);ctx.rotate(degree * Math.PI / 180);ctx.drawImage(image, x, y);image.style.display = "none";

The above code looks quite a lot. In fact, the core method is only the rotate and drawimage mentioned just now. But note that when the canvas is rotated, the width and height of the canvas may be reversed, the drawn coordinates may also be reversed, so we switched the degree, and processed the reverse results at different angles. Finally, we hidden the original image and used the drawn canvas for display.

The main process of rotating images on the front-end is as follows. The remaining problem is that the following function is used to determine whether to use canvas or filter in the browser:

function supportCanvas(){return !!document.createElement('canvas').getContext;}

Set the above Code in a function, and slightly modify it. Add a button to the outside to rotate the image cyclically. below is the complete code of this demo. HTML:

<P> <input type = "button" value = "Rotate" id = "rorate_button"/> </P>  <canvas id = "image_canvas"> </canvas>

Javascript:

// Canvas capability detection var suppcanvas canvas = !! Document. createelement ('canvas '). getcontext; // main function imagerotate (degree, image, canvasid) {If (! Supportcanvas) {image. style. filter = 'progid: DXImageTransform. microsoft. basicimage (rotation = '+ Degree/90 +') ';} else {var canvas = document. getelementbyid (canvasid); var CTX = canvas. getcontext ('2d '); var width = image. width, height = image. height, x = 0, y = 0; Switch (degree) {Case 90: width = image. height; Height = image. width; y = image. height * (-1); break; Case 180: x = image. width * (-1); y = image. h Eight * (-1); break; Case 270: width = image. height; Height = image. width; X = image. width * (-1); break;} canvas. setattribute ('width', width); canvas. setattribute ('height', height); CTX. rotate (degree * Math. PI/180); CTX. drawimage (image, x, y); image. style. display = "NONE" ;}}// bind var degree = 0 to the event from the initial perspective; var image = document. getelementbyid ("rotate_demo"); document. getelementbyid ("rorate_button "). onclick = Function () {degree + = 90; Degree = degree = 360? 0: degree; imagerotate (degree, image, 'image _ canvas ');};
References:
  • Msdn ---- rotation Property
  • MDC --- using images

From: http://www.jsmix.com/javascript/image-rotate-without-correspondence.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.