我担心像素化“库”是不可能的,因为它是如何创建像素化的。它只是使用原始宽度和高度来拉伸原始图像的缩小版本 - 因此没有任何单独的矩形。
但是,您可以自己执行此操作。基本上你已经确定了你的马赛克的pixelSize - 例如16。现在循环整个图像并在屏幕坐标处获得单个1x1像素的颜色,它是pixelSize的倍数。最后将每个像素位置、大小和颜色存储在一个数组中。
现在您可以循环遍历数组并将各个矩形绘制到画布上,或者根据需要为它们设置动画。
这是一个例子:
Square = function(x, y, w, h, color) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.color = color;
}
var squares = new Array();
var canvas = document.createElement("canvas");
var canvas2 = document.createElement("canvas");
canvas.width = canvas2.width = 200;
canvas.height = canvas2.height = 100;
var context = canvas.getContext("2d");
var context2 = canvas2.getContext("2d");
document.body.appendChild(canvas);
document.body.appendChild(canvas2);
function rgbToHex(r, g, b) {
return ((r << 16) | (g << 8) | b).toString(16);
}
var img = new Image();
img.onload = function() {
context.drawImage(this, 0, 0);
var pixelSize = 8;
var ySteps = Math.round(this.height / pixelSize);
var xSteps = Math.round(this.width / pixelSize);
var colorX;
var colorY;
var square;
var color;
var hexColor;
for (var i = 0; i <= ySteps; i++) {
if (i == ySteps) {
colorY = pixelSize * (i - 1);
} else {
colorY = pixelSize * (i);
}
for (var j = 0; j <= xSteps; j++) {
if (j == xSteps) {
colorX = pixelSize * (j - 1);
} else {
colorX = pixelSize * (j);
}
color = context.getImageData(j * pixelSize, i * pixelSize, 1, 1).data;
hexColor = "#" + ("000000" + rgbToHex(color[0], color[1], color[2])).slice(-6);
square = new Square(j * pixelSize, i * pixelSize, pixelSize, pixelSize, hexColor);
squares.push(square);
}
}
for (var a = 0; a < squares.length; a++) {
square = squares[a];
context2.fillStyle = square.color;
context2.fillRect(square.x, square.y, square.width, square.height);
}
}
img.crossOrigin = "anonymous";
img.src = "https://picsum.photos/id/76/200/100";