感觉这个代码还真的是挺好的啊,这个是比较不错,大家直接看吧。
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
<script>
var pixelation = 40;
function focusImage(context, imageObj, sourceWidth, sourceHeight, destX, destY) {
var sourceX = destX;
var sourceY = destY;
var imageData = context.getImageData(sourceX, sourceY, sourceWidth, sourceHeight);
var data = imageData.data;
for(var y = 0; y < sourceHeight; y += pixelation) {
for(var x = 0; x < sourceWidth; x += pixelation) {
var red = data[((sourceWidth * y) + x) * 4];
var green = data[((sourceWidth * y) + x) * 4 + 1];
var blue = data[((sourceWidth * y) + x) * 4 + 2];
for(var n = 0; n < pixelation; n++) {
for(var m = 0; m < pixelation; m++) {
if(x + m < sourceWidth) {
data[((sourceWidth * (y + n)) + (x + m)) * 4] = red;
data[((sourceWidth * (y + n)) + (x + m)) * 4 + 1] = green;
data[((sourceWidth * (y + n)) + (x + m)) * 4 + 2] = blue;
}
}
}
}
}
// overwrite original image
context.putImageData(imageData, destX, destY);
pixelation -= 1;
}
var fps = 20;
// frames / second
var timeInterval = 1000 / fps;
// milliseconds
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
var sourceWidth = imageObj.width;
var sourceHeight = imageObj.height;
var destX = canvas.width / 2 - sourceWidth / 2;
var destY = canvas.height / 2 - sourceHeight / 2;
var intervalId = setInterval(function() {
context.drawImage(imageObj, destX, destY);
if(pixelation < 1) {
clearInterval(intervalId);
}
else {
focusImage(context, imageObj, sourceWidth, sourceHeight, destX, destY);
}
}, timeInterval);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
</script>
</body>
</html>