[英]Use Javascript and Canvas to move a pixel from an image
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. 我不确定“物理移动”的意思,但是可以使用ctx.putImageData()
将像素应用于画布内的其他位置。
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. 另外,您应该将所有此imageData
操作都放在onload
函数中,因为在您的示例中,调用ctx.getImageData()
时仍不加载图像,因此您要处理空白像素。
Note also that for security reason, you cannot use getImageData()
on an image loaded from a different domain. 还要注意,出于安全原因,不能在从其他域加载的图像上使用getImageData()
。 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. 所以我认为您的示例将引发类型为Uncaught Error: SECURITY_ERR: DOM Exception 18
,因为图像是从Instagram加载的。
I think this tutorial might help you: 我认为本教程可以为您提供帮助:
https://developer.mozilla.org/en/Canvas_tutorial/Basic_animations https://developer.mozilla.org/en/Canvas_tutorial/Basic_animations
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.