


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="" alt="Sample code sharing for JavaScript image cropping without deformation (picture)" > </p> <img class="base-image hide-image" data-dojo-attach-point="baseImage" data-dojo-attach-event="mousedown:_onViewerMouseDown,mouseup:_onViewerMouseUp" alt="Sample code sharing for JavaScript image cropping without deformation (picture)" > <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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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