Skip to content

Instantly share code, notes, and snippets.

@kylejlin
Last active July 13, 2016 21:43
Show Gist options
  • Save kylejlin/7f8fac6e3d747588d6b1020e9bf166cc to your computer and use it in GitHub Desktop.
Save kylejlin/7f8fac6e3d747588d6b1020e9bf166cc to your computer and use it in GitHub Desktop.
/**
* Copyright (c) 2016 Kyle Lin
* This is a script to download an n by n image file of a rectangle.
*/
/**
* Downloads an image of a filled rectangle.
* @param {number} width The width of the rectangle.
* @param {number} height The height of the rectangle.
* @param {(string|CanvasGradient|CanvasPattern)} fillStyle The fill style of the rectangle.
* @param {{imageType: string, downloadName: string}} downloadOptions The imageType is the image type to be passed to
* canvas.toDataURL and downloadName is the name of the file to be downloaded (including the extension).
*/
function downloadRectImg(width, height, fillStyle, downloadOptions) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
a = document.createElement('a'),
imageType = downloadOptions.imageType
downloadName = downloadOptions.downloadName;
canvas.width = width;
canvas.height = height;
ctx.fillStyle = fillStyle;
ctx.fillRect(0, 0, width, height);
a.href = canvas.toDataURL(imageType, 1);
a.download = downloadName;
a.click();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment