Implementation
You need to edit the image before uploading the image. I chose the cropperjs plug-in.
The main idea of creating a circular chart is to first set the visible area in the Image Selection box to a circle, and then select a circular chart based on the source image when uploading the image through Js, upload the selected circle to the background interface.
- Use CSS to set the Cropper selection box to a circle
.cropper-view-box, .cropper-face { border-radius: 50%;}
- Use canvas to select a circle based on the source Image
Function getroundedcanvas () {var crop = (...). data ("Cropper"); // obtain the crop object var sourcecanvas = crop. getcroppedcanvas (); var canvas = document. createelement ('canvas '); var context = canvas. getcontext ('2d '); var width = sourcecanvas. width; var Height = sourcecanvas. height; canvas. width = width; canvas. height = height; context. imagesmoothingenabled = true; context. drawimage (sourcecanvas, 0, 0, width, height); context. globalcompositeoperation = 'destination-in'; context. beginpath (); context. ARC (width/2, height/2, math. min (width, height)/2, 0, 2 * Math. pi, true); context. fill (); Return canvas ;}
- You can use step 2 to obtain a canvas of a circular image. Note that if you convert the image to a jpg image by using todataurl, the background color of the obtained circular image may become black, because the original transparency attribute will be lost during JPG conversion, here I solve this problem by setting the image conversion format to PNG in a unified manner. The following code is attached:
var dataurl=canvas.toDataURL("image/png");var arr = dataurl.split(‘,‘), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);while(n--){ u8arr[n] = bstr.charCodeAt(n);}var filename=(...);var f=new File([u8arr],filename,{type:"image/png"});
Documents consulted during the process:
- Cropperjs circular Processing
- Cropperjs documentation
- Canvas Reference Manual
Cropper image editing plug-in