


Sample code sharing for JavaScript image cropping without deformation (picture)
I have recently browsed a lot of website image cropping effects. Most of the methods are as shown in the picture below (borrowing a picture from Script Home). Select the appropriate position by changing the size of the cropping box.
But this article introduces another cropping method. The cropping box is determined by the developer, and the image size is determined by the user. Select the appropriate position by zooming and dragging the image, and always maintain the aspect ratio of the image in the process, as shown in the picture above right.
This method mainly has the following advantages:
#The width and height of the cropping frame are consistent with the actual aspect ratio used to prevent image deformation problems.
Does not limit the display size of the picture and ensures the original proportion of the picture. The original size can be obtained by scaling
For partial cropping It is more friendly. For example, to capture a very small part of a high-definition picture, we only need to enlarge the picture and drag it into the cropping box. However, other methods require the cropping box to be adjusted to a very small size, which is not conducive to user operation.
After talking about it, I should also talk about the shortcomings. The shortcoming is that the difficulty is increased by an order of magnitude. . . .
The main idea is to use two pictures, position them absolutely, put one inside the cropping box and the other outside the cropping box and set the transparent effect, cropping boxoverflow is hidden, keeping the two pictures absolutely synchronized at all times.
<p class="jimu-crop-image" data-dojo-attach-point="cropSection"> <p class="viewer-box" data-dojo-attach-point="viewerBox"> <p class="viewer-content" data-dojo-attach-point="viewerContent"> <img class="viewer-image hide-image" data-dojo-attach-point="viewerImage" src=""> </p> <img class="base-image hide-image" data-dojo-attach-point="baseImage" data-dojo-attach-event="mousedown:_onViewerMouseDown,mouseup:_onViewerMouseUp"> <p class="controller"> <p class="zoom-out" data-dojo-attach-event="click:_onZoomOutClick">-</p> <p class="slider" data-dojo-attach-point="sliderNode"> <p class="button" data-dojo-attach-point="sliderButton" data-dojo-attach-event="mousedown:_onSliderMouseDown,mouseup:_onSliderMouseUp"></p> <p class="horizontal"></p> </p> <p class="zoom-in" data-dojo-attach-event="click:_onZoomInClick">+</p> </p> </p> </p>
First bind the mousemove and mousedown events of document in postCreate. You can continue after the mouse leaves the workspace. Drag or zoom. The next main work is in startup and _initfunction. Friends who are not familiar with dojo only need to know that postCreate will be executed before startup.
startup: function() { var timeOut = /data:image\/(.*);base64/.test(this.imageSrc) ? 50 : 500; var tic = lang.hitch(this, function() { var imageStyle = html.getComputedStyle(this.baseImage); var imageWidth = parseFloat(imageStyle.width); console.log('image width', imageWidth); if (isFinite(imageWidth) && imageWidth > 0) { this._init(); } else { setTimeout(tic, timeOut); } }); setTimeout(tic, timeOut); }, _init: function() { debugger; var cropSectionStyle = html.getComputedStyle(this.cropSection); var cropSectionContentBox = html.getContentBox(this.cropSection); var imageStyle = html.getComputedStyle(this.baseImage); var imageWidth = parseFloat(imageStyle.width); var imageHeight = parseFloat(imageStyle.height); var imageRadio = imageWidth / imageHeight; this._maxImageWidth = imageWidth; this._maxImageHeight = imageHeight; if (imageHeight < this.realHeight && imageWidth < this.realWidth) { alert('image is too smaller to display'); return; } //create a box which keep the ratio of width and height to full fill the content of popup this.idealWidth = this.realWidth; this.idealHeight = this.realHeight; this.ratio = this.ratio ? this.ratio : this.realWidth / this.realHeight; if (this.ratio >= 1) { if (this.realWidth <= cropSectionContentBox.w) { this.idealWidth += (cropSectionContentBox.w - this.realWidth) / 2; } else { this.idealWidth = cropSectionContentBox.w; } this.idealHeight = this.idealWidth / this.ratio; } else { if (this.realHeight <= cropSectionContentBox.h) { this.idealHeight += (cropSectionContentBox.h - this.idealHeight) / 2; } else { this.idealHeight = cropSectionContentBox.h; } this.idealWidth = this.idealHeight * this.ratio; } html.setStyle(this.viewerBox, { width: this.idealWidth + 'px', height: this.idealHeight + 'px' }); var paddingTop = Math.abs((parseFloat(cropSectionStyle.height) - this.idealHeight) / 2); html.setStyle(this.cropSection, { 'paddingTop': paddingTop + 'px', 'paddingBottom': paddingTop + 'px' }); // keep original ratio of image if (imageRadio >= 1) { if (this.idealHeight * imageRadio >= this.idealWidth) { html.setStyle(this.viewerImage, 'height', this.idealHeight + 'px'); html.setStyle(this.baseImage, 'height', this.idealHeight + 'px'); } else { var properlyHeight = this._findProperlyValue(0, this.idealWidth, this.idealWidth, function(p) { return p * imageRadio; }); html.setStyle(this.viewerImage, 'height', properlyHeight + 'px'); html.setStyle(this.baseImage, 'height', properlyHeight + 'px'); } } else { if (this.idealWidth / imageRadio >= this.idealHeight) { html.setStyle(this.viewerImage, 'width', this.idealWidth + 'px'); html.setStyle(this.baseImage, 'width', this.idealWidth + 'px'); } else { var properlyWidth = this._findProperlyValue(0, this.idealHeight, this.idealHeight, function(p) { return p / imageRadio; }); html.setStyle(this.viewerImage, 'width', properlyWidth + 'px'); html.setStyle(this.baseImage, 'width', properlyWidth + 'px'); } } query('.hide-image', this.domNode).removeClass('hide-image'); imageStyle = html.getComputedStyle(this.baseImage); imageWidth = parseFloat(imageStyle.width); imageHeight = parseFloat(imageStyle.height); this._minImageWidth = imageWidth; this._minImageHeight = imageHeight; this._currentImageWidth = imageWidth; this._currentImageHeight = imageHeight; this._currentTop = -(imageHeight - this.idealHeight) / 2; this._currentLeft = -(imageWidth - this.idealWidth) / 2; html.setStyle(this.baseImage, { top: this._currentTop + 'px', left: this._currentLeft + 'px' }); html.setStyle(this.viewerImage, { top: this._currentTop + 'px', left: this._currentLeft + 'px' }); //sometimes zoomratio < 1; it's should be not allowed to zoom this._zoomRatio = this._maxImageWidth / this._minImageWidth; if (!this._latestPercentage) { this._latestPercentage = 0; } },
The following things are done here:
Wait for the image to be loaded, obtain the original size of the image, which will be used in subsequent calculations of the scaling factor
While ensuring the aspect ratio of the cropping area, let the cropping area fill the work area as much as possible. The most important thing in cropping work here is to prevent the image from being deformed, so as long as the aspect ratio is consistent, the cropped area can be appropriately enlarged.
While maintaining the original aspect ratio of the picture, keep the picture as close to the cropping frame as possible
Set the initial position of the picture after the computer calculation is completed. Center the cropping frame relative to the picture
The process of panning is relatively simple. You only need to record the relative position changes of the mouse during the movement, and continuously change the left and top in the upper left corner of the picture. preventDefault in dragstart and selectstart events prevents elements from being selected and turning blue.
_resetImagePosition: function(clientX, clientY) { var delX = clientX - this._currentX; var delY = clientY - this._currentY; if (this._currentTop + delY >= 0) { html.setStyle(this.baseImage, 'top', 0); html.setStyle(this.viewerImage, 'top', 0); this._currentY = clientY; this._currentTop = 0; } else if (this._currentTop + delY <= this._maxOffsetTop) { html.setStyle(this.baseImage, 'top', this._maxOffsetTop + 'px'); html.setStyle(this.viewerImage, 'top', this._maxOffsetTop + 'px'); this._currentY = clientY; this._currentTop = this._maxOffsetTop; } else { html.setStyle(this.baseImage, 'top', this._currentTop + delY + 'px'); html.setStyle(this.viewerImage, 'top', this._currentTop + delY + 'px'); this._currentY = clientY; this._currentTop += delY; } if (this._currentLeft + delX >= 0) { html.setStyle(this.baseImage, 'left', 0); html.setStyle(this.viewerImage, 'left', 0); this._currentX = clientX; this._currentLeft = 0; } else if (this._currentLeft + delX <= this._maxOffsetLeft) { html.setStyle(this.baseImage, 'left', this._maxOffsetLeft + 'px'); html.setStyle(this.viewerImage, 'left', this._maxOffsetLeft + 'px'); this._currentX = clientX; this._currentLeft = this._maxOffsetLeft; } else { html.setStyle(this.baseImage, 'left', this._currentLeft + delX + 'px'); html.setStyle(this.viewerImage, 'left', this._currentLeft + delX + 'px'); this._currentX = clientX; this._currentLeft += delX; } },
The main principle of scaling is tokeep the relative position of the center point of the cropping frame unchanged before and after scaling.
In order to move the center point of the scaled original cropping box back to its original position, we need to calculate the median of the two: image size Change amount, the amount of movement of the upper left corner of the picture.
var delImageWidth = this._minImageWidth * (this._zoomRatio - 1) * leftPercentage / 100; var delImageHeight = this._minImageHeight * (this._zoomRatio - 1) * leftPercentage / 100; var imageStyle = html.getComputedStyle(this.baseImage); this._currentLeft = parseFloat(imageStyle.left); this._currentTop = parseFloat(imageStyle.top); var delImageLeft = (Math.abs(this._currentLeft) + this.idealWidth / 2) * ((this._minImageWidth + delImageWidth) / this._currentImageWidth - 1); var delImageTop = (Math.abs(this._currentTop) + this.idealHeight / 2) * ((this._minImageWidth + delImageWidth) / this._currentImageWidth - 1);
Where _zoomRatio = _maxImageWidth / _minImageWidth; _maxImageWidth is the original size of the picture, _minImageWidth is the minimum width that makes the picture close to the cropping box.
leftPercentage is the displacement percentage of the sliding button relative to the sliding bar.
_currentLeft and _currentTop are the absolute position of the picture relative to the cropping frame before this scaling (position: absolute).
_currentImageWidth and _currentImageHeight are the size of the image before this scaling.
The only thing left to do is to prevent the blank phenomenon in the cropping box. Suppose the user enlarges the picture and drags the picture to the border to coincide with the border of the cropping box. At this time, if the picture is reduced, the cropping box will be A blank appears. In order to prevent this situation, we also need to take corresponding measures.
When the upper left border of the image coincides with the upper left border of the cropping box, no matter how it is zoomed out, the left and top of the image will always be zero, and only the size of the image will be changed.
When the lower right border of the picture coincides with the lower right border of the cropping box, the appropriate left and top can be calculated based on the size of the picture and the size of the cropping box
//prevent image out the crop box if (leftPercentage - _latestPercentage >= 0) { console.log('zoomin'); html.setStyle(this.baseImage, { top: this._currentTop -delImageTop + 'px', left: this._currentLeft -delImageLeft + 'px' }); html.setStyle(this.viewerImage, { top: this._currentTop -delImageTop + 'px', left: this._currentLeft -delImageLeft + 'px' }); } else { console.log('zoomout'); var top = 0; var left = 0; if (this._currentTop - delImageTop >= 0) { top = 0; } else if (this._currentTop - delImageTop + this._minImageHeight + delImageHeight <= this.idealHeight) { top = this.idealHeight - this._minImageHeight - delImageHeight; } else { top = this._currentTop - delImageTop; } console.log(this._currentLeft, delImageLeft); if (this._currentLeft - delImageLeft >= 0) { left = 0; } else if (this._currentLeft - delImageLeft + this._minImageWidth + delImageWidth <= this.idealWidth) { left =this.idealWidth - this._minImageWidth - delImageWidth; } else { left = this._currentLeft - delImageLeft; } html.setStyle(this.baseImage, { top: top + 'px', left: left + 'px' }); html.setStyle(this.viewerImage, { top: top + 'px', left: left + 'px' }); }
The above is the implementation of the client ideas. All codes, browser support: modern browsers and ie9+, ie8 will also be supported later.
服务器端使用nodejs+express框架,主要代码如下:
/********** body: { imageString: base64 code maxSize: w,h cropOptions: w,h,t,l } ************/ exports.cropImage = function(req, res) { var base64Img = req.body.imageString; if(!/^data:image\/.*;base64,/.test(base64Img)){ res.send({ success: false, message: 'Bad base64 code format' }); } var fileFormat = base64Img.match(/^data:image\/(.*);base64,/)[1]; var base64Data = base64Img.replace(/^data:image\/.*;base64,/, ""); var maxSize = req.body.maxSize; maxSize = maxSize.split(','); var cropOptions = req.body.cropOptions; cropOptions = cropOptions.split(','); try{ var buf = new Buffer(base64Data, 'base64'); var jimp = new Jimp(buf, 'image/' + fileFormat, function() { var maxW = parseInt(maxSize[0], 10); var maxH = parseInt(maxSize[1], 10); var cropW = parseInt(cropOptions[0], 10); var cropH = parseInt(cropOptions[1], 10); var cropT = parseInt(cropOptions[2], 10); var cropL = parseInt(cropOptions[3], 10); this.resize(maxW, maxH) .crop(cropT, cropL, cropW, cropH); }); jimp.getBuffer('image/' + fileFormat, function(b) { var base64String = "data:image/" + fileFormat + ";base64," + b.toString('base64'); res.send({ success: true, source: base64String }); }); }catch(err) { logger.error(err); res.send({ success: false, message: 'unable to complete operations' }); } };
The above is the detailed content of Sample code sharing for JavaScript image cropping without deformation (picture). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
