【问题标题】:Getting pixel data on setInterval with canvas使用画布在 setInterval 上获取像素数据
【发布时间】:2015-01-04 01:06:10
【问题描述】:

我想制作一个由粒子组成的动画字母表。基本上,粒子从一种字母形状转变为另一种字母形状。

我的想法是在画布上快速填充字母作为文本(如帧),获取像素数据并将粒子放置在 setInterval 上的正确位置。我现在有这个扫描屏幕的代码:

var ctx = canvas.getContext('2d'),
    width = ctx.canvas.width,
    height = ctx.canvas.height,

    particles = [],
    gridX = 8,
    gridY = 8;

function Particle(x, y) {
    this.x = x;
    this.y = y;
}

// fill some text
ctx.font = 'bold 80px sans-serif';
ctx.fillStyle = '#ff0';
ctx.fillText("STACKOVERFLOW", 5, 120);

// now parse bitmap based on grid
var idata = ctx.getImageData(0, 0, width, height);

// use a 32-bit buffer as we are only checking if a pixel is set or not
var buffer32 = new Uint32Array(idata.data.buffer);

// using two loops here, single loop with index-to-x/y is also an option
for(var y = 0; y < height; y += gridY) {
  for(var x = 0; x < width; x += gridX) {

    //buffer32[] will have a value > 0 (true) if set, if not 0=false
    if (buffer32[y * width + x]) {
      particles.push(new Particle(x, y));
    }
  }
}

// render particles
ctx.clearRect(0, 0, width, height);

particles.forEach(function(p) {
  ctx.fillRect(p.x - 2, p.y - 2, 4, 4); // just squares here
})

但这样我只显示一个词,全程没有任何变化。另外,我想最初设置 200 个粒子并根据像素数据重新组织它们,而不是在每次扫描时创建它们。你将如何重写代码,所以每 1500 毫秒我可以传递一个不同的字母并用粒子渲染它?

【问题讨论】:

  • 对于动画,只需处理一个起点/终点,并在动画循环中插入:jsbin.com/nomiloleri/1/edit?js,output 对于逐字母特征,还有更多工作:你必须使用 measureText,绘制在辅助画布上,getImageData 并为您添加到当前粒子集的这个新字母构建一组新粒子。这需要一些组织才能避免混乱。祝你好运!
  • 谢谢,伙计!当我在辅助画布上绘制时,是否应该将其插入 DOM 并实际绘制在屏幕上以使其正常工作,或者我可以仅使用它来填充文本(同样,不渲染任何内容)并获取其 imageData?另外,为什么我要为每个新字母在粒子阵列中添加新粒子?我如何制作 100 个粒子并将它们转换为新形状,而不制作新粒子或拼接粒子阵列?另外,由于我对 JS 很陌生,你能告诉我如何构建和编写这样的应用程序吗?提前致谢!

标签: html animation canvas


【解决方案1】:

希望这段代码的不同部分应该足够清楚:有可以绘制和更新的粒子,fillParticle 会从文本字符串中生成粒子,spawnChars 会定期渲染文本的新部分.

它工作得很好,如果你愿意,可以使用参数,它们都在小提琴的开头。
您可能希望通过避免使用全局变量和创建类来使这段代码更简洁。

http://jsbin.com/jecarupiri/1/edit?js,output

// --------------------
// parameters

var text = 'STACKOVERFLOW';
var fontHeight = 80;
var gridX = 4,
    gridY = 4;
var partSize = 2; 
var charDelay = 400; // time between two chars, in ms
var spead = 80; // max distance from start point to final point
var partSpeed = 0.012;

// --------------------
var canvas = document.getElementById('cv'),
    ctx = canvas.getContext('2d'),
    width = ctx.canvas.width,
    height = ctx.canvas.height,
    particles = [];

ctx.translate(0.5,0.5);

// --------------------
// Particle class
function Particle(startX, startY, finalX, finalY) {
    this.speed = partSpeed*(1+Math.random()*0.5);
    this.x = startX;
    this.y = startY;

    this.startX = startX;
    this.startY = startY;
    this.finalX =finalX;
    this.finalY =finalY;
    this.parameter = 0;
    this.draw = function() {
        ctx.fillRect(this.x - partSize*0.5, this.y - partSize*0.5, partSize, partSize);
    };
    this.update = function(p) {
       if (this.parameter>=1) return;
       this.parameter += partSpeed;
       if (this.parameter>=1) this.parameter=1;
       var par = this.parameter;
       this.x = par*this.finalX + (1-par)*this.startX;
       this.y = par*this.finalY + (1-par)*this.startY;
   };
}

// --------------------
// Text spawner

function fillParticle(text, offx, offy,  spread) {
   // fill some text
   tmpCtx.clearRect(0,0,tmpCtx.canvas.width, tmpCtx.canvas.height);
   tmpCtx.font = 'bold ' + fontHeight +'px sans-serif';
   tmpCtx.fillStyle = '#A40';
   tmpCtx.textBaseline ='top';
   tmpCtx.textAlign='left';
   tmpCtx.fillText(text, 0, 0);
   //
   var txtWidth = Math.floor(tmpCtx.measureText(text).width);
   // now parse bitmap based on grid
   var idata = tmpCtx.getImageData(0, 0, txtWidth, fontHeight);

   // use a 32-bit buffer as we are only checking if a pixel is set or not
   var buffer32 = new Uint32Array(idata.data.buffer);

   // using two loops here, single loop with index-to-x/y is also an option
   for(var y = 0; y < fontHeight; y += gridY) {
     for(var x = 0; x < txtWidth; x += gridX) {
        //buffer32[] will have a value > 0 (true) if set, if not 0=false
        if (buffer32[y * txtWidth + x]) {
           particles.push(new Particle(offx + x+Math.random()*spread - 0.5*spread, 
                                  offy + y+Math.random()*spread - 0.5*spread, offx+x, offy+y));
        }
    }
  }  
  return txtWidth;
}

var tmpCv = document.createElement('canvas');
// uncomment for debug
//document.body.appendChild(tmpCv);
var tmpCtx = tmpCv.getContext('2d');

// --------------------------------
// spawn the chars of the text one by one

var charIndex = 0;
var lastSpawnDate = -1;
var offX = 30;
var offY = 30;

function spawnChars() {
  if (charIndex>= text.length) return;
  if (Date.now()-lastSpawnDate < charDelay) return;
  offX += fillParticle(text[charIndex], offX, offY, spead);
  lastSpawnDate = Date.now();
  charIndex++;                           
}


// --------------------------------

function render() {
   // render particles
   particles.forEach(function(p) { p.draw();
   });  
}

function update() {
   particles.forEach(function(p) { p.update(); } );    
}

// --------------------------------
//  animation
function animate(){
   requestAnimationFrame(animate);
   ctx.clearRect(0, 0, width, height);
   render();
    update();
  //
  spawnChars();
}

// launch : 
animate();

【讨论】:

  • @Georgi B. Nikolov:我注意到您在 StackOverflow 上提出了很多问题并收到了有用的答案。由于您是一个相对较新的用户,我要提一下 StackOverflow 上的传统做法是让您单击最能满足您问题需求的答案上的复选标记。此复选标记让回答者知道您收到了很好的答案,他们不需要尝试进一步回答您的问题。此复选标记也是对帮助您解答的人的“感谢”。
猜你喜欢
  • 2014-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
  • 2011-01-11
  • 2012-02-23
  • 2017-05-21
  • 1970-01-01
相关资源
最近更新 更多