canvas is converted to pictures and forced to be downloaded by browser

canvas to image and download



Most people will use the canvas2image.js plug-in to implement the conversion from canvas to image download, but the downloaded image does not have a suffix. The principle of plug-in source code is very simple. We can do some work on this basis to achieve the desired effect

Principle of canvas2image.js

  * saveAsImage
  * @param canvasElement
  * @param {String} image type
  * @param {Number} [optional] png width
  * @param {Number} [optional] png height
 var saveAsImage = function (canvas, width, height, type) {
     if ($support.canvas && $support.dataURL) {
         if (typeof canvas == "string") { canvas = document.getElementById(canvas); }
         if (type == undefined) { type = 'png'; }
         type = fixType(type);
         if (/bmp/.test(type)) {
             var data = getImageData(scaleCanvas(canvas, width, height));
             var strData = genBitmapImage(data);
             saveFile(makeURI(strData, downloadMime));
         } else {
             var strData = getDataURL(canvas, type, width, height);
             saveFile(strData.replace(type, downloadMime));

What did it do? In fact, getDataURL is to set the width and height of canvas and then convert canvas to base64 through toDataURL. In strData.replace(type, downloadMime), set the MIME type to image / octet stream to force the browser to download. What the saveFile method does is to download the image by window.location.href


The images downloaded by plug-ins are not suffixed. We can achieve the effect of plug-ins by ourselves

var linkDom = document.createElement('a')
          linkDom.href = canvas.toDataURL()
 = Date.parse(new Date()) + '.' + 'jpg'
          var event = document.createEvent('MouseEvents')
          event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)

In fact, just a few lines of code have done what plug-ins should do, and the pictures have suffixes.
In fact, the code is very simple. Create an a tag, set the base 64 code of the canvas as the href, download the name and suffix of the downloaded image, and then initialize an event to trigger the a tag

Tags: Javascript github

Posted on Sun, 01 Dec 2019 17:52:18 -0800 by Divine Winds