Canvas realizes rounded image (processing original image is rectangle or square)

/**
         * Generate image thumbnails
         * @param {[type]} img image (img) object or address
         * @param {[type]} width Thumbnail width
         * @param {[type]} height Thumbnail height
         * @return {[type]} return base64 png image string
         */
        function thumb_image(img, width, height) {
            if (typeof img !== 'object') {
                var has = new Image();
                img.crossOrigin = ''
                tem.src = img;
                img = has;
            }
            var _canv = document.createElement('canvas');
            _canv.width = width;
            _canv.height = height;
            _canv.getContext("2d").drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);
            return _canv.toDataURL();
        }
        
        // yuan_image('./res/demo.jpg')
        /**
         * Process the picture into a circle, if it is not a square, it is processed according to the radius of half of the smallest side
         * @param {[type]} img image (img) object or address
         * @return {[type]} return base64 png image string
         */
        function yuan_image(img) {
            if (typeof img !== 'object') {
                var has = new Image();
                img.crossOrigin = ''
                tem.src = img;
                img = has;
            }
            var w, h, _canv, _contex, cli;
            if (img.width > img.height) {
                w = img.height;
                h = img.height;
            } else {
                w = img.width;
                h = img.width;
            }
            _canv = document.createElement('canvas');
            _canv.width = w;
            _canv.height = h;
            _contex = _canv.getContext("2d");
            cli = {
                x: w / 2,
                y: h / 2,
                r: w / 2
            };
            _contex.clearRect(0, 0, w, h);
            _contex.save();
            _contex.beginPath();
            _contex.arc(cli.x, cli.y, cli.r, 0, Math.PI * 2, false);
            _contex.clip();
            _contex.drawImage(img, 0, 0);
            console.log (_canv.toDataURL ())
            return _canv.toDataURL();
        }

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325274085&siteId=291194637