我一直在尝试使用canvas元素,并且很好奇如何取消效果。如何使用画布和javascript使图像像素化
我从教程和演示的集合中找到了一些我需要的东西,但是我需要一些帮助来获得剩余的方法。我正在寻找的是在mouseover
上对图像进行像素化,然后在mouseout
上重新对焦/取消像素化。当鼠标悬停在主传送带下面的块上时,您可以在http://www.cropp.com/上看到效果的一个很好的示例。
这是一个link to a fiddle我开始了。小提琴不能工作,因为你不能使用跨域图像(womp womp),但你仍然可以看到我的代码到目前为止。将鼠标悬停在画布对象上时,我可以对图像进行像素化处理,但这与我试图获得的内容有些相反。任何帮助或建议将不胜感激。
var pixelation = 40,
fps = 120,
timeInterval = 1000/fps,
canvas = document.getElementById('photo'),
context = canvas.getContext('2d'),
imgObj = new Image();
imgObj.src = 'images/me.jpg';
imgObj.onload = function() {
context.drawImage(imgObj, 0, 0);
};
canvas.addEventListener('mouseover', function() {
var interval = setInterval(function() {
context.drawImage(imgObj, 0, 0);
if (pixelation < 1) {
clearInterval(interval);
pixelation = 40;
} else {
pixelate(context, canvas.width, canvas.height, 0, 0);
}
}, timeInterval);
});
function pixelate(context, srcWidth, srcHeight, xPos, yPos) {
var sourceX = xPos,
sourceY = yPos,
imageData = context.getImageData(sourceX, sourceY, srcWidth, srcHeight),
data = imageData.data;
for (var y = 0; y < srcHeight; y += pixelation) {
for (var x = 0; x < srcWidth; x += pixelation) {
var red = data[((srcWidth * y) + x) * 4],
green = data[((srcWidth * y) + x) * 4 + 1],
blue = data[((srcWidth * y) + x) * 4 + 2];
for (var n = 0; n < pixelation; n++) {
for (var m = 0; m < pixelation; m++) {
if (x + m < srcWidth) {
data[((srcWidth * (y + n)) + (x + m)) * 4] = red;
data[((srcWidth * (y + n)) + (x + m)) * 4 + 1] = green;
data[((srcWidth * (y + n)) + (x + m)) * 4 + 2] = blue;
}
}
}
}
}
// overwrite original image
context.putImageData(imageData, xPos, yPos);
pixelation -= 1;
}
更新你的小提琴以通过数据网址获得实际图像:http://jsfiddle.net/xDt7U/1/ – Chad