Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PNG transparency support #6

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 19 additions & 12 deletions 8bit.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,29 +17,36 @@
root.eightBit = factory();
}
} (this, function () {
// Necessary to hide the original image with PNG transparency
const invisibleCanvas = document.createElement('canvas');
const invisibleCtx = invisibleCanvas.getContext('2d');

/**
* Draws a pixelated version of an image in a given canvas
* Draws a pixelated version of an image in a given canvas.
* @param {object} canvas - a canvas object
* @param {object} image - an image HTMLElement object
* @param {number} scale - the scale factor: between 0 and 100
* @param {number} quality - the new quality: between 0 and 100
*/
var eightBit = function (canvas, image, scale) {
scale *= 0.01;

canvas.width = image.width;
canvas.height = image.height;
const eightBit = function (canvas, image, quality) {
quality /= 100;

var scaledW = canvas.width * scale;
var scaledH = canvas.height * scale;
canvas.width = invisibleCanvas.width = image.width;
canvas.height = invisibleCanvas.height = image.height;

var ctx = canvas.getContext('2d');
const scaledW = canvas.width * quality;
const scaledH = canvas.height * quality;
const ctx = canvas.getContext('2d');

ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;

ctx.drawImage(image, 0, 0, scaledW, scaledH);
ctx.drawImage(canvas, 0, 0, scaledW, scaledH, 0, 0, image.width, image.height);
// Draws image scaled to desired quality on the invisible canvas, then
// draws that scaled image on the visible canvas.
ctx.clearRect(0, 0, canvas.width, canvas.height);
invisibleCtx.clearRect(0, 0, invisibleCtx.canvas.width, invisibleCtx.canvas.height);
invisibleCtx.drawImage(image, 0, 0, scaledW, scaledH);
ctx.drawImage(invisibleCtx.canvas, 0, 0, scaledW, scaledH, 0, 0, canvas.width, canvas.height);
};

return eightBit;
Expand Down