Home > Web Front-end > JS Tutorial > body text

Sample code sharing for JavaScript image cropping without deformation (picture)

黄舟
Release: 2017-03-13 16:51:14
Original
1758 people have browsed it

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:

  1. #The width and height of the cropping frame are consistent with the actual aspect ratio used to prevent image deformation problems.

  2. 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

  3. 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>
Copy after login

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(&#39;image width&#39;, 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(&#39;image is too smaller to display&#39;);
                    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 + &#39;px&#39;,
                    height: this.idealHeight + &#39;px&#39;
                });

                var paddingTop = Math.abs((parseFloat(cropSectionStyle.height) - this.idealHeight) / 2);
                html.setStyle(this.cropSection, {
                    &#39;paddingTop&#39;: paddingTop + &#39;px&#39;,
                    &#39;paddingBottom&#39;: paddingTop + &#39;px&#39;
                });

                // keep original ratio of image
                if (imageRadio >= 1) {
                    if (this.idealHeight * imageRadio >= this.idealWidth) {
                        html.setStyle(this.viewerImage, &#39;height&#39;, this.idealHeight + &#39;px&#39;);
                        html.setStyle(this.baseImage, &#39;height&#39;, this.idealHeight + &#39;px&#39;);
                    } else {
                        var properlyHeight = this._findProperlyValue(0, this.idealWidth, this.idealWidth, function(p) {
                            return p * imageRadio;
                        });
                        html.setStyle(this.viewerImage, &#39;height&#39;, properlyHeight + &#39;px&#39;);
                        html.setStyle(this.baseImage, &#39;height&#39;, properlyHeight + &#39;px&#39;);
                    }
                } else {
                    if (this.idealWidth / imageRadio >= this.idealHeight) {
                        html.setStyle(this.viewerImage, &#39;width&#39;, this.idealWidth + &#39;px&#39;);
                        html.setStyle(this.baseImage, &#39;width&#39;, this.idealWidth + &#39;px&#39;);
                    } else {
                        var properlyWidth = this._findProperlyValue(0, this.idealHeight, this.idealHeight, function(p) {
                            return p / imageRadio;
                        });
                        html.setStyle(this.viewerImage, &#39;width&#39;, properlyWidth + &#39;px&#39;);
                        html.setStyle(this.baseImage, &#39;width&#39;, properlyWidth + &#39;px&#39;);
                    }
                }

                query(&#39;.hide-image&#39;, this.domNode).removeClass(&#39;hide-image&#39;);

                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 + &#39;px&#39;,
                    left: this._currentLeft + &#39;px&#39;
                });
                html.setStyle(this.viewerImage, {
                    top: this._currentTop + &#39;px&#39;,
                    left: this._currentLeft + &#39;px&#39;
                });
                //sometimes zoomratio < 1; it&#39;s should be not allowed to zoom
                this._zoomRatio = this._maxImageWidth / this._minImageWidth;

                if (!this._latestPercentage) {
                    this._latestPercentage = 0;
                }
            },
Copy after login

The following things are done here:

  1. 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

  2. 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.

  3. While maintaining the original aspect ratio of the picture, keep the picture as close to the cropping frame as possible

  4. 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, &#39;top&#39;, 0);
                    html.setStyle(this.viewerImage, &#39;top&#39;, 0);
                    this._currentY = clientY;
                    this._currentTop = 0;
                } else if (this._currentTop + delY <= this._maxOffsetTop) {
                    html.setStyle(this.baseImage, &#39;top&#39;, this._maxOffsetTop + &#39;px&#39;);
                    html.setStyle(this.viewerImage, &#39;top&#39;, this._maxOffsetTop + &#39;px&#39;);
                    this._currentY = clientY;
                    this._currentTop = this._maxOffsetTop;
                } else {
                    html.setStyle(this.baseImage, &#39;top&#39;, this._currentTop + delY + &#39;px&#39;);
                    html.setStyle(this.viewerImage, &#39;top&#39;, this._currentTop + delY + &#39;px&#39;);
                    this._currentY = clientY;
                    this._currentTop += delY;
                }

                if (this._currentLeft + delX >= 0) {
                    html.setStyle(this.baseImage, &#39;left&#39;, 0);
                    html.setStyle(this.viewerImage, &#39;left&#39;, 0);
                    this._currentX = clientX;
                    this._currentLeft = 0;
                } else if (this._currentLeft + delX <= this._maxOffsetLeft) {
                    html.setStyle(this.baseImage, &#39;left&#39;, this._maxOffsetLeft + &#39;px&#39;);
                    html.setStyle(this.viewerImage, &#39;left&#39;, this._maxOffsetLeft + &#39;px&#39;);
                    this._currentX = clientX;
                    this._currentLeft = this._maxOffsetLeft;
                } else {
                    html.setStyle(this.baseImage, &#39;left&#39;, this._currentLeft + delX + &#39;px&#39;);
                    html.setStyle(this.viewerImage, &#39;left&#39;, this._currentLeft + delX + &#39;px&#39;);
                    this._currentX = clientX;
                    this._currentLeft += delX;
                }
            },
Copy after login

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);
Copy after login

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(&#39;zoomin&#39;);
                    html.setStyle(this.baseImage, {
                        top: this._currentTop -delImageTop + &#39;px&#39;,
                        left: this._currentLeft -delImageLeft + &#39;px&#39;
                    });
                    html.setStyle(this.viewerImage, {
                        top: this._currentTop -delImageTop + &#39;px&#39;,
                        left: this._currentLeft -delImageLeft + &#39;px&#39;
                    });
                } else {
                    console.log(&#39;zoomout&#39;);
                    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 + &#39;px&#39;,
                        left: left + &#39;px&#39;
                    });
                    html.setStyle(this.viewerImage, {
                        top: top + &#39;px&#39;,
                        left: left + &#39;px&#39;
                    });
                }
Copy after login

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: &#39;Bad base64 code format&#39;
    });
  }
  var fileFormat = base64Img.match(/^data:image\/(.*);base64,/)[1];
  var base64Data = base64Img.replace(/^data:image\/.*;base64,/, "");
  var maxSize = req.body.maxSize;
  maxSize = maxSize.split(&#39;,&#39;);
  var cropOptions = req.body.cropOptions;
  cropOptions = cropOptions.split(&#39;,&#39;);

  try{
    var buf = new Buffer(base64Data, &#39;base64&#39;);
    var jimp = new Jimp(buf, &#39;image/&#39; + 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(&#39;image/&#39; + fileFormat, function(b) {
      var base64String = "data:image/" + fileFormat + ";base64," + b.toString(&#39;base64&#39;);
      res.send({
        success: true,
        source: base64String
      });
    });
  }catch(err) {
    logger.error(err);
    res.send({
      success: false,
      message: &#39;unable to complete operations&#39;
    });
  }
};
Copy after login


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!

source:php.cn
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
Popular Tutorials
More>
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!