How to rotate images using HTML5 canvas? (Example demonstration)

青灯夜游
Release: 2020-10-20 17:38:11
forward
4060 people have browsed it

How to rotate images using HTML5 canvas? (Example demonstration)

Recently, I suddenly wanted to study the function of rotating images in js. I won’t talk about the previous implementation methods first. HTML5 is very good now. Let’s mainly understand the image rotation in HTML5.

Example demonstration:

http://www.imqing.com/demo/rotateImg.html

Principle: Use canvas object to rotate.

Implementation method: First create a canvas element, and then draw the img element into the canvas. However, in fact, this is the default situation, when the image is not rotated. If the picture needs to be rotated 90 degrees, you need to rotate the canvas 90 degrees before drawing.

The description is as follows:

The internal rotation principle is like this. The coordinates of the picture are calculated from the upper left corner. To the right is the positive x direction, and down is the positive y direction. When rotating the canvas When, the coordinates are actually rotating, so the final drawing method is different.

At that time, I also used picpick to measure the coordinates of the starting point after rotating a certain angle, and then I realized that the original rotation was like this.

Code:

  
Copy after login

Explanation: There is no need to explain canvas.width and height, it should be. You shouldn’t need to rotate, right? The key isdrawImage(img, x, y);

x and y refer to the point from which to start drawing. Because the entire coordinate system is rotated, x and y are different. , for examplestep=1, the picture is rotated 90 degrees to the right, that is, the coordinate system is rotated 90 degrees, then the starting position should bex = 0, y= img.height

The above is the detailed content of How to rotate images using HTML5 canvas? (Example demonstration). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!