Convert SVG to image (JPEG, PNG, etc.) in the browser

前端 未结 9 1045
春和景丽
春和景丽 2020-11-21 23:38

I want to convert SVG into bitmap images (like JPEG, PNG, etc.) through JavaScript.

9条回答
  •  一向
    一向 (楼主)
    2020-11-21 23:57

    I wrote this ES6 Class which does the Job.

    class SvgToPngConverter {
      constructor() {
        this._init = this._init.bind(this);
        this._cleanUp = this._cleanUp.bind(this);
        this.convertFromInput = this.convertFromInput.bind(this);
      }
    
      _init() {
        this.canvas = document.createElement("canvas");
        this.imgPreview = document.createElement("img");
        this.imgPreview.style = "position: absolute; top: -9999px";
    
        document.body.appendChild(this.imgPreview);
        this.canvasCtx = this.canvas.getContext("2d");
      }
    
      _cleanUp() {
        document.body.removeChild(this.imgPreview);
      }
    
      convertFromInput(input, callback) {
        this._init();
        let _this = this;
        this.imgPreview.onload = function() {
          const img = new Image();
          _this.canvas.width = _this.imgPreview.clientWidth;
          _this.canvas.height = _this.imgPreview.clientHeight;
          img.crossOrigin = "anonymous";
          img.src = _this.imgPreview.src;
          img.onload = function() {
            _this.canvasCtx.drawImage(img, 0, 0);
            let imgData = _this.canvas.toDataURL("image/png");
            if(typeof callback == "function"){
                callback(imgData)
            }
            _this._cleanUp();
          };
        };
    
        this.imgPreview.src = input;
      }
    }
    

    Here is how you use it

    let input = "https://restcountries.eu/data/afg.svg"
    new SvgToPngConverter().convertFromInput(input, function(imgData){
        // You now have your png data in base64 (imgData). 
        // Do what ever you wish with it here.
    });
    

    If you want a vanilla JavaScript version, you could head over to Babel website and transpile the code there.

提交回复
热议问题