I'm interested in moving a pixel (eventually all of them) from an image drawn on canvas. This is the sample code i'm working off and i believe it does some pretty standard stuff in terms of drawing the image:
var images = [ // predefined array of used images
'http://distilleryimage6.instagram.com/928c49ec07d411e19896123138142014_7.jpg'
];
var iActiveImage = 0;
$(function(){
// drawing active image
var image = new Image();
image.onload = function () {
ctx.drawImage(image, 0, 0, image.width, image.height); // draw the image on the canvas
}
image.src = images[iActiveImage];
// creating canvas object
canvas = document.getElementById('panel');
ctx = canvas.getContext('2d');
console.log(ctx);
var imageData = ctx.getImageData(200, 150, 1, 1);
var pixel = imageData.data;
});
So i have this but could someone point me in the right direction of doing something like picking a pixel at random from the image and physically moving it somewhere else on the page? Is this possible?
Thanks
I'm not sure what you mean by "physically moving it", but you can use ctx.putImageData()
to apply the pixel elsewhere inside the canvas.
var imageData = ctx.getImageData(200, 150, 1, 1);
var pixel = imageData.data;
// You can even get or set the color or alpha of the pixel. (values between 0-255)
var r = pixel[0];
var g = pixel[1];
var b = pixel[2];
var a = pixel[3];
ctx.putImageData(imageData, x, y); // Where x y are the new coordinates.
Also, you should put all this imageData
manipulation inside the onload
function, because in your example, the image is still not loaded when you call ctx.getImageData()
, so you're manipulating blank pixels.
Note also that for security reason, you cannot use getImageData()
on an image loaded from a different domain. So I think your example will throw an exception of type Uncaught Error: SECURITY_ERR: DOM Exception 18
, because the image is loaded from Instagram.
I think this tutorial might help you:
https://developer.mozilla.org/en/Canvas_tutorial/Basic_animations
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.