Coder Social home page Coder Social logo

glitch-canvas's Introduction

Build Status Greenkeeper badge

glitch-canvas

downloads

$ npm install glitch-canvas

what is it?

glitch-canvas is a javascript library for applying a glitch effect to a canvas element. it can be used to transform images to look like this:

glitched image

for a live example, you can check out my jpg-glitch editor online.

how to use it

this library can be used in web browsers as well as in node. it supports loading as an AMD module, as a CommonJS module or a global variable..

a simple example:

	glitch( { seed: 25, quality: 30 } )
		.fromImage( image )
		.toDataURL()
		.then( function( dataURL ) {
			var glitchedImg = new Image();
			glitchedImg.src = dataURL;
		} );

as you can see, there are three calls happening:

  1. glitch() is called with the glitch parameters
  2. then fromImage() is called with the input image as parameter
  3. and finally toDataURL() is called to output a dataURL.

when using the library, always follow these three steps:

  1. glitch
  2. input
  3. output

all input and output methods are asynchronous and use promises for flow control.

for an explanation of all available methods and parameters, check out the reference section below.

you can find more examples for both node and the browser in the examples folder of this repository.

reference

glitch()

glitch() can take the following parameters that control how the glitched image is going to look:

// the parameters listed are the default params

var glitchParams = {
	seed:       25, // integer between 0 and 99
	quality:    30, // integer between 0 and 99
	amount:     35, // integer between 0 and 99
	iterations: 20  // integer
};

please note: depending on the size, quality and contents of the source image and the number of iterations, the visual effect of the seed and amount parameters can be marginal or not even noticeable.

it returns an object containing all input methods.

fromImage()

fromImage() expects an Image object as its only parameter. it returns an object containing all input methods.

example:

var image = new Image();

image.onload = function () {
	glitch()
		.fromImage( image )
		.toDataURL()
		.then( function( dataURL ) {
			var glitchedImg = new Image();
			glitchedImg.src = dataURL;
			document.body.appendChild( glitchedImg );
		} );
};

image.src = 'lincoln.jpg'

please note: this method is not available in node. important: when using the library in a browser, make sure the image was loaded before glitching it.

fromImageData()

fromImageData() expects an ImageData object as its only parameter. it returns an object containing all input methods.

example:

var canvas = document.createElement( 'canvas' );
var ctx = canvas.getContext( '2d' );

ctx.fillStyle = 'red';
ctx.fillRect( 30, 30, 90, 45 );
ctx.fillStyle = 'green';
ctx.fillRect( 10, 20, 50, 60 );

var imageData = ctx.getImageData( 0, 0, canvas.width, canvas.height );

glitch()
	.fromImageData( imageData )
	.toDataURL()
	.then( function( dataURL ) {
		var glitchedImg = new Image();
		glitchedImg.src = dataURL;
		document.body.appendChild( glitchedImg );
	} );

fromBuffer()

fromBuffer() expects a Buffer object as its only parameter. it returns an object containing all input methods.

it uses image#src=buffer from node-canvas internally.

example:

var fs = require('fs');

fs.readFile( './lincoln.jpg', function ( err, buffer ) {
	if ( err ) { throw err; }
		
	glitch()
		.fromBuffer( buffer )
		.toBuffer()
		.then( function ( glitchedBuffer ) {
			fs.writeFile( __dirname + '/glitched-lincoln.png', glitchedBuffer, function ( err ) {
				if ( err ) { throw err; }
				console.log( 'file glitched.' );
			} );
		} );
} );

please note: this method is only available in node.

fromStream()

fromStream() expects a ReadableStream object as its only parameter. it returns an object containing all input methods.

it uses image#src=buffer from node-canvas internally.

example:

var fs = require('fs');

var inputStream = fs.createReadStream( './lincoln.jpg' );
var outputStream = fs.createWriteStream( './glitched-lincoln.png' );

glitch()
	.fromStream( inputStream )
	.toPNGStream()
	.then( function ( pngStream ) {
		pngStream.on( 'data', function ( chunk ) { outputStream.write( chunk ); } );
		pngStream.on( 'end', function () { console.log( 'png file saved.' ); } );
	} );

please note: this method is only available in node. currently, theres no input sanitation for this method, so you'll want to make sure that the input stream contains an image.

toDataURL()

toDataURL() does not take any parameters. it returns a String containing the base64-encoded image url.

example:

var image = new Image();

image.onload = function () {
	glitch()
		.fromImage( image )
		.toDataURL()
		.then( function( dataURL ) {
			var glitchedImg = new Image();
			glitchedImg.src = dataURL;
			document.body.appendChild( glitchedImg );
		} );
};

image.src = 'lincoln.jpg'

toImageData()

toImageData() does not take any parameters. it returns an ImageData object.

example:

var image = new Image();

image.onload = function () {
	glitch()
		.fromImage( image )
		.toImageData()
		.then( function ( imageData ) {
			var canvas = document.createElement( 'canvas' );
			var ctx = canvas.getContext( '2d' );
			ctx.putImageData( imageData, 0, 0 );

			document.body.appendChild( canvas );
		} );
};

image.src = 'lincoln.jpg'

toImage()

toImage() does not take any parameters. it returns an Image object.

example:

var image = new Image();

image.onload = function () {
	glitch()
		.fromImage( image )
		.toImage()
		.then( function ( glitchedImage ) {
			document.body.appendChild( glitchedImage );
		} );
};

image.src = 'lincoln.jpg'

please note: this method is only available in the browser.

toBuffer()

toBuffer() doesn't take any parameters. it uses canvas#tobuffer from node-canvas internally.

it returns a Buffer object.

example:

var fs = require('fs');

fs.readFile( './lincoln.jpg', function ( err, buffer ) {
	if ( err ) { throw err; }
		
	glitch()
		.fromBuffer( buffer )
		.toBuffer()
		.then( function ( imageBuffer ) {
			fs.writeFile( './glitched-lincoln.png', imageBuffer, function ( err ) {
				if ( err ) { throw err; }
				console.log( 'created a pdf file.' );
			} );
		} );
} );

please note: this method is only available in node.

toJPGStream()

toJPGStream() can take the following parameters:

var jpgStreamParams = {
	bufsize: 4096,          // output buffer size in bytes
	quality: 75,            // jpg quality (0-100) default: 75
	progressive: false      // true for progressive compression
};

it uses canvas#jpegstream() from node-canvas internally.

it returns a JPEGStream object.

example:

var fs = require('fs');
fs.readFile( __dirname + '/lincoln.jpg', function ( err, buffer ) {
		if ( err ) {
			throw err;
		}

		var fileStream = fs.createWriteStream( __dirname + '/glitched-lincoln.jpg' );
		
		glitch()
			.fromBuffer( buffer )
			.toJPGStream()
			.then( function ( jpgStream ) {
				jpgStream.on( 'data', function ( chunk ) { fileStream.write( chunk ); } );
				jpgStream.on( 'end', function () { console.log( 'file glitched.' ); } );
			} );
	} );

please note: this method is only available in node.

toJPEGStream()

see toJPGStream().

toPNGStream()

toPNGStream() doesn't take any parameters. it uses canvas#pngstream() from node-canvas internally.

it returns a PNGStream object.

example:

var fs = require('fs');
fs.readFile( __dirname + '/lincoln.jpg', function ( err, buffer ) {
		if ( err ) { throw err;	}

		var fileStream = fs.createWriteStream( __dirname + '/glitched-lincoln.png' );
		
		glitch()
			.fromBuffer( buffer )
			.toPNGStream()
			.then( function ( pngStream ) {
				pngStream.on( 'data', function ( chunk ) { fileStream.write( chunk ); } );
				pngStream.on( 'end', function () { console.log( 'file glitched.' ); } );
			}, function( err ) {
				console.log( 'There was an error', err );
			} );
	} );

please note: this method is only available in node.

development

npm run build will build the node-ready and browser-ready versions, which are saved to the dist-node and dist directories.

npm run test will run the tests in both the browser and node.

you can find the source code for the library in the src folder. it is using es6-style syntax.

license

mit

third party code

most of the folder structure and the npm script setup were taken from nonalnawson's hello javascript repo (Apache-2.0 license).

dependencies:

glitch-canvas in the wild

implementations in other languages

if you want to add your site or project to one of these lists, you can create a pull request or send me an email.

missing somehing?

found a bug? missing a feature? instructions unclear? are you using this library in an interesting project? maybe have a look at the issues, open a pull request and let me know. thanks!

most importantly

thank you for taking a look at this repo. have a great day :)

glitch-canvas's People

Contributors

dependabot[bot] avatar elifitch avatar greenkeeper[bot] avatar muffinista avatar patrickpietens avatar snorpey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

glitch-canvas's Issues

ReferenceError: window is not defined

Hi,
is there any way to use it on nodeJs server without any view or client rendering ?

I used your exemple :

var inputStream = fs.createReadStream(filename);
var outputStream = fs.createWriteStream( 'glitched/'+filename );

glitch()
  .fromStream( inputStream )
  .toPNGStream()
  .then( function ( pngStream ) {
      pngStream.on( 'data', function ( chunk ) { outputStream.write( chunk ); } );
      pngStream.on( 'end', function () { console.log( 'png file saved.' ); } );
  } );

but as a result i've only this error : ReferenceError: window is not defined

Any help ?

how to destroy the glitch instance ?

for example am using it inside a vuejs component but even when destroying the component, reinit glitch again still shows the same old results.


PS

am trying to do something similar to the demo but i keep getting different results, any help on how to recreate it is appreciated.

Parameters

It would be great to have some explanations for the parameters being used.

I can't figure out what difference does "seed" have.

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Error installing glitch-canvas from npm

Hi snorpey,

First of all thanks for sharing your script with the community.

I have been trying to run it for a while now but I am quite a newbie with node and npm and when i try to install it i get some errors, which i don't know if are node/npm or glitch-canvas related. I would appreciate if you could give me a hand with it!

Thanks :)

npm ERR! Darwin 15.6.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "test-node"
npm ERR! node v7.4.0
npm ERR! npm v4.1.1
npm ERR! code ELIFECYCLE
npm ERR! [email protected] test-node: mocha ./test/test-node.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] test-node script 'mocha ./test/test-node.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the glitch-canvas package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! mocha ./test/test-node.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs glitch-canvas
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls glitch-canvas
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! /Users/hugocifre/Desktop/glitch-canvas-master/npm-debug.log

npm ERR! Darwin 15.6.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "test"
npm ERR! node v7.4.0
npm ERR! npm v4.1.1
npm ERR! code ELIFECYCLE
npm ERR! [email protected] test: npm run test-node && npm run test-browser
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] test script 'npm run test-node && npm run test-browser'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the glitch-canvas package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! npm run test-node && npm run test-browser
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs glitch-canvas
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls glitch-canvas
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! /Users/hugocifre/Desktop/glitch-canvas-master/npm-debug.log

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/canvas):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] install: node-gyp rebuild
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
npm ERR! Darwin 15.6.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install"
npm ERR! node v7.4.0
npm ERR! npm v4.1.1
npm ERR! code ELIFECYCLE
npm ERR! [email protected] prepublish: npm run build && npm run test
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] prepublish script 'npm run build && npm run test'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the glitch-canvas package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! npm run build && npm run test
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs glitch-canvas
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls glitch-canvas
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! /Users/hugocifre/Desktop/glitch-canvas-master/npm-debug.log

Use web workers

I am currently using this library to apply a glitch effect to the images every 2.5 seconds. But after a while it starts lagging massively and halting the main thread. Wouldn't it be better to use web workers for the processing of the images?

How to make this loop

if i want this to run more than once on an image like here https://augaware.org/

what is the best way?

i have this function, would i just call it over and over again to generate the random glitch?

imageGlitch: function () {
        var item = document.getElementsByClassName("js-top-places"),
            canvas = item[0],
            ctx = item[0].getContext('2d'),
            path = "resources/images/test/",
            w = canvas.clientWidth,
            h = (616 / 555) * canvas.clientWidth;
            canvas.height = h;
            canvas.width = w;

        // the parameters listed are the default params
        var glitchParams = {
            seed: Math.floor(Math.random() * (99 - 0 + 1)) + 0, // integer between 0 and 99 - default 20
            quality:  Math.floor(Math.random() * (80 - 40 + 1)) + 40, // integer between 0 and 99 - default 30
            amount: Math.floor(Math.random() * (99 - 25 + 1)) + 25, // integer between 0 and 99 - default 35
            iterations: Math.floor(Math.random() * (25 - 5 + 1)) + 25 // integer - default 20
        };

        var image = new Image();

        image.onload = function () {
            glitch(glitchParams)
                .fromImage(image)
                .toImageData()
                .then(function (imageData) {
                    ctx.drawImage(image, 0, 0, w, h, 0, 0, w, h);
                    ctx.putImageData(imageData, 0, 0);
                });
        };

        image.src = path + canvas.getAttribute("data-img");

    },

An in-range update of uglify-js is breaking the build 🚨


🚨 Reminder! Less than one month left to migrate your repositories over to Snyk before Greenkeeper says goodbye on June 3rd! 💜 🚚💨 💚

Find out how to migrate to Snyk at greenkeeper.io


The devDependency uglify-js was updated from 3.9.2 to 3.9.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

uglify-js is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v3.9.3

 

Commits

The new version differs by 35 commits.

  • 30ed8f5 v3.9.3
  • dc9e7cd suppress ufuzz false positives (#3893)
  • 76f40e2 fix corner case in collapse_vars (#3892)
  • 8024f7f fix corner case in ie8 (#3890)
  • eb7fa25 fix corner case in evaluate (#3888)
  • ee7647d fix corner case in collapse_vars (#3885)
  • bd2f53b fix corner case in evaluate (#3883)
  • e8a7956 fix corner case in reduce_vars (#3881)
  • 2b24dc2 fix corner cases in evaluate & reduce_vars (#3879)
  • 35cc5aa extend --reduce-test to cover minify() bugs (#3876)
  • c1dd49e fix corner case in comparisons (#3877)
  • c76ee4b enhance if_return (#3875)
  • e23bf48 enhance evaluate & reduce_vars (#3873)
  • 7e0ad23 retain @__PURE__ call when return value is used (#3874)
  • 63adfb1 fix corner case in hoist_props (#3872)

There are 35 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Minimum canvas size constraint ?

Woaw, it looks like I'm creating the first issue, what a feeling, anyway, so here is the problem :
There seems to be a minimum canvas size under which the script simply doesn't work.

How to reproduce : If you resize the canvases in the examples (either global or AMD) to a small size (I found 60 width and 60 height to be the threshold for me) it doesn't glitch any more.

I don't know if it's base64 related or not because I can't find the bug in the image data manipulations.

Good luck !

"Image corrupt or truncated" error thrown in Firefox

Hi there,

I'm having this weird issue: sometimes (not each time but often), Firefox raises this error. With some digging I found it comes from this line:
img.src = byteArrayToBase64(byte_array);
The error is followed by the image url in base64 format.

I tried to do the byteArray -> base64 conversion with an external library and got a more detailed error:
Uncaught Error: Invalid string. Length must be a multiple of 4.

which I got on this line:

    byte_array = base64Module.toByteArray(base64); // Processing with external base64 lib
    // byte_array = base64ToByteArray(base64); // Original processing

This error is raised on all browsers this time (it comes from the external base64 library). Indeed, the length is not a multiple of 4.

I tried with a simple image (background + text) made in Photoshop, same result.
At this point I'm not sure if it's because Firefox doesn't support a slightly off image whereas chrome does, or if it's something that can be fixed.

I'm not really comfortable with digging into the base64 conversion code :D Please let me know if you have any clue though.

QUESTION Canvas 2.0?

Is there any word, news or hope of a Canvas 2.0 supported version? I would love to use this, but I use Canvas 2.0 sadly.

Only works with Jpeg input by design?

Is it by design that png input results in the following error:

 Error: Unsupported marker type 0x59
        at setSource (/node_modules/canvas/lib/image.js:91:13)
        at Image.set (/node_modules/canvas/lib/image.js:40:9)
        at /node_modules/glitch-canvas/dist/glitch-canvas-node.js:197:15
glitch().fromStream(canvas.createPNGStream()).toBuffer() // returns error
glitch().fromStream(canvas.createJPEGStream()).toBuffer() // works

Wrap glitch-canvas in a timer function

More of a question:

I'm trying to wrap a canvas in a timer so it redraws a glitched image from random params every n seconds. Looking at the HTML example you posted, which function should be called in the timer? loadImage requires a callback, but I can't seem to figure out which callback should be used.

An in-range update of uglify-es is breaking the build 🚨

Version 3.0.26 of uglify-es just got published.

Branch Build failing 🚨
Dependency uglify-es
Current Version 3.0.25
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As uglify-es is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪

Status Details
  • continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Release Notes v3.0.26

 

Commits

The new version differs by 7 commits.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

is it possible to use glitched image as a backround for a DIV?

Hi,
is it possible to use the output as a background for a DIV? If yes, how?

A code like this, which is for static images:

<div class="fullscreen background" style="background-image:url('http://www.minimit.com/images/picjumbo.com_IMG_6648.jpg');" data-img-width="1600" data-img-height="1064">

I'm getting some errors while using glitch-canvas

Hi, I'm using this module for my bot made in discord.js, and sometimes I get random errors like

Error: Invalid component ID 33 in SOS

Error: Invalid component ID 12 in SOS

Error: Bogus marker length

Error: Huffman table 0x03 was not defined

My code is:

const Discord = require('discord.js')
const Canvas = require('canvas')
const fs = require('fs')
const db = require('megadb')
const bsonDB = require("bsondb");
const { createCanvas, loadImage } = require('canvas');
const request = require('node-superfetch');
const glitch = require('glitch-canvas')



module.exports = {
  name: 'glitch',
  description: '',
  async execute(client, message, args) {
    let user = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.member
    let image = user.user.displayAvatarURL({ format: 'jpeg', size: 1024 }) //url below
    const { body } = await request.get(image);
    const data = await loadImage(body);
    const canvas = createCanvas(data.width < 250 ? 278 : data.width, data.height < 250 ? 278 : data.height); //using this because I think it happens with small images
    const ctx = canvas.getContext('2d');
    ctx.drawImage(data, 0, 0, canvas.width, canvas.height);
    const attachment = canvas.toBuffer();
    glitch({ seed: Math.floor(Math.random() * 20), itinerations: Math.floor(Math.random() * 20), amount: Math.floor(Math.random() * 20) })
      .fromBuffer(attachment)
      .toBuffer()
      .then(function(glitchedBuffer) {
        message.channel.send({
          files: [{
            attachment: glitchedBuffer,
            name: 'glitch.jpeg'
          }]


        })
      }).catch(error => {
        message.channel.send('Please, use the command another time. ' + error)
      })


  }
}

Currently I'm using this image

Thanks in advance

Flip options?

Hi, this is really awesome, great work.

A part of the aesthetic I'm not too keen on when glitching images (manually or using this library) is that images generally always have the same characteristics from top to bottom. I.e. the images have a tenancy to 'slip' in one direction and the changes in the 'lines of glitch' within the glitched image as you look from the top of the image to the bottom generally have a 'step' up (look like steps).

To try and get around this, so the glitch effect is kind of more uniform, a nice feature would be flip the canvas vertically before an iteration, and then flip it back for the next iteration, and so on. And the final result would be the same way up as your started. I've hacked this in to the current version of the library I'm using but it's not very pretty.

Here's an example of with and without flipping during the glitch process:
glitch

For my purposes it has given me better results.

Essentially I used this before every iteration:
ctx.setTransform(1, 0, 0, -1, 0, canvas.height);

Interested to hear your thoughts!

Doesn't work in Chrome (version 50.0.2661.94)

I loaded up examples\browser-example.html and got this:

chrome_50

Console:

glitch-canvas-with-polyfills.js:381 Uncaught (in promise) DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.(…)


In Firefox 46, only the toDataURL part works. There are no errors in the console.

Corrupting JPEG

Hi snorpey,
I am trying to understand why corrupting single bytes in the JPEG file affects a much bigger part of the picture. Let take as an example https://snorpey.github.io/jpg-glitch/ with arguments:

  • amount: 1,
  • seed: 57,
  • iterations: 1

This is the resulting image:
image

Passing these arguments to glitchByteArray function would result in one iteration, hence single byte corruption. The resulting image though has a much bigger part changed in a way, that you can still see the original part, but in a different color range.
In the "Info" section on that page one can read "Because of the way JPEG encoding works, the corrupted file still shows a corrupted image.", which links to Wikipedia, but I still have a hard time understanding why that happens.
From what I understand encoding into JPEG format means:

  1. Downsampling single bytes,
  2. Dividing image into 8x8 pixel blocks,
  3. Transforming 8x8 pixel matrices into 8x8 real numbers matrices,
  4. Using Huffman encoding on each of the resulting matrices, but iterating in a zig-zag way instead of left-right and top-down.

Could you please explain why corrupting a single byte affects a bigger part of the picture? And if my encoding description is not correct, could you please correct me?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.