Skip to content

Instantly share code, notes, and snippets.

@eberlitz
Created November 23, 2017 11:03
Show Gist options
  • Save eberlitz/c8d617ed20d7acbf9738c1d8ac784bc1 to your computer and use it in GitHub Desktop.
Save eberlitz/c8d617ed20d7acbf9738c1d8ac784bc1 to your computer and use it in GitHub Desktop.
How to load image pixels in javascript
function loadImage(canvas, src, x, y, width, height, opt_callback) {
var img = new window.Image();
img.crossOrigin = '*';
img.onload = function () {
var context = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
context.drawImage(img, x, y, width, height);
opt_callback && opt_callback();
img = null;
};
img.src = src;
};
var canvas = document.createElement('canvas');
var width = 512;
var height = 512;
canvas.width = width;
canvas.height = height;
loadImage(
canvas,
'https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png',
0, 0,
width, height,
() => {
var context = canvas.getContext('2d');
var imageData = context.getImageData(0, 0, width, height);
console.log(imageData);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment