On one of the projects, it was necessary to make a crochet for avatars uploaded by users. Standard solutions, such as Jcrop, after selecting the area, send coordinates to the server, and the image itself needs to be cropped on the server. Meanwhile, modern browsers have already reached the point where such actions can be performed immediately on the client. This prompted me to write my crooner using canvas, which would perform all actions on the client and send the finished image as a base64 string to the server. In addition to speeding up and unloading the server, it also allows us to immediately change the user's avatar on the page, without uploading it from the server.Rect . There is nothing magic in it - properties with coordinates, methods for determining the hitting of a point and updating coordinates. The EvroneCrop class EvroneCrop responsible for creating a canvas, drawing it on top of the image, hanging handlers and saving the cropped image in data.drawImage() method, the selected area is drawn to the temporary canvas, and using the toDataURL() method from the canvas we obtain the resulting image, which can be passed as base64 to the server and save. encoded_image = params[:image].sub('data:image/png;base64,', '') avatar_io = FilelessIO.new(Base64.decode64(encoded_image)) avatar_io.original_filename = "avatar.png" # , CarrierWave Rails.logger.info "IO: #{avatar_io.inspect}" @user.avatar = avatar_io @user.save $(this).evroneCrop({ preview: '#preview1', // img, size: {w: 150, h: 150}, // ratio: 1, // , - setSelect: 'center', // log: true // }); setSelect can take the center value, automatically calculate the center of the image and the size of the selection, or it can take an object {x:0, y: 0, w: 100, h: 100} and set the selection to a specified position. If you have the ratio parameter set, you do not need to transfer the height in the object for setSelect .ratio takes a number greater than zero and fixes the sides with a ratio of lengths equal to that number. For example, you can pass 1 for a square or 16/9 for an aspect ratio of 16 to 9.toDataURL(); There is a way out with sales on a flash , but hands have not reached it yet.Source: https://habr.com/ru/post/133362/
All Articles