JSFiddle - React, Tailwind, and code Playground

by upgradingdave

HTML

<h4>Original Image</h4>
<img width="300px" src="https://s3.amazonaws.com/www.upgradingdave.com/blog/img/crabs-1.jpg"/>

<h4>Resized to 576x324</h4>
<p>Clicking the link should download the image as expected</p>
<img width="150" id="img576"/>
<a id="a576"></a>

<h4>Resized to 2048x1152</h4>
<p>Clicking the link doesn't do anything</p>
<img width="200" id="imgBig"/>
<a id="aBig"></a>

<h4>Resized to 2048x1152 Using Blob</h4>
<p></p>
<img width="200" id="imgBlob"/>
<a id="aBlob"></a>

JavaScript

var makeButton = function (canvas, a) {
  a.href = canvas.toDataURL("image/jpg", 0.7);
  a.download = "example.jpg";
  var linkText = document.createTextNode(canvas.width + "px");
  a.appendChild(linkText);
};

var resizeOnLoad = function(width, height, a) {
  var result = function () {
    console.log("image loaded");
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = width;
    canvas.height = height;
  
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    makeButton(canvas, a);
  };
  return result;
};

if (!HTMLCanvasElement.prototype.toBlob) {
 Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
  value: function (callback, type, quality) {

    var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
        len = binStr.length,
        arr = new Uint8Array(len);

    for (var i=0; i<len; i++ ) {
     arr[i] = binStr.charCodeAt(i);
    }

    callback( new Blob( [arr], {type: type || 'image/png'} ) );
  }
 });
}

var makeButtonUsingBlob = function (canvas, a) {
  canvas.toBlob(function(blob) {
    a.href = window.URL.createObjectURL(blob);
    a.download = "example.jpg";
    var linkText = document.createTextNode(canvas.width + "px");
    a.appendChild(linkText);
  }, "image/jpeg", 0.7);
};

var resizeWithBlob = function(width, height, a) {
  var result = function () {
    console.log("image loaded");
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = width;
    canvas.height = height;
  
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    makeButtonUsingBlob(canvas, a);
  };
  return result;
}

var img = document.getElementById("img576");
var a   = document.getElementById("a576");
img.onload = resizeOnLoad(576, 324, a);
img.src = "https://s3.amazonaws.com/www.upgradingdave.com/blog/img/crabs-1.jpg";

img = document.getElementById("imgBig");
a   = document.getElementById("aBig");
img.onload =...