如果可以在JavaScript中对像素化的画布正方形进行动画处理

时间:2019-06-15 05:35:24

标签: javascript animation html5-canvas pixelate

因此您可以通过在画布上像this一样绘制图像来像素化:

/* css */
.pixelate {
  image-rendering: optimizeSpeed;
  image-rendering: -moz-crisp-edges;
  image-rendering: -o-crisp-edges;
  image-rendering: -webkit-crisp-edges;
  image-rendering: crisp-edges;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: pixelated;
  -ms-interpolation-mode: nearest-neighbor;
}

// js
var canvas = document.createElement('canvas')
var context = canvas.getContext('2d')

context.webkitImageSmoothingEnabled = false
context.mozImageSmoothingEnabled = false
context.msImageSmoothingEnabled = false
context.imageSmoothingEnabled = false

enter image description here

我想知道是否有一种方法可以弄清楚这些正方形在画布中的位置以及它们是什么颜色,以便您可以对它们进行处理(例如,在这种情况下)为它们设置动画,使其看起来像它们是波光粼粼的,或者可能更简单,只是像波浪一样来回移动它们。

1 个答案:

答案 0 :(得分:1)

恐怕 pixelate “库”是不可能的,因为它如何创建像素化。它只是使用原始的宽度和高度来拉伸原始图像的按比例缩小版本-因此没有任何单独的矩形。

但是,您可以自己执行此操作。基本上,您确实要确定马赛克的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";