2014-11-06 25 views
0

我試圖複製這種效果,但我覺得教程提供了極爲難走:http://tympanus.net/Tutorials/InteractiveTypographyEffects/index3.html獲取填充像素位置的x和y的值在畫布

基本上,我想,以填補文本到畫布非常快速(如單幀),獲取圖像數據(逐個掃描整個頁面的像素),如果一個像素被填充,則將粒子推入x和y位置。

我知道getImageData如何運作以及如何掃描像素一個接一個,比如這個:

var numPixels = imageData.width*imageData.height; 

for (var i = 0; i < numPixels; i++) { 
    pixels[i*4] = 255; // Red 
    pixels[i*4+1] = 0; // Green 
    pixels[i*4+2] = 0; // Blue 
    pixels[i*4+3] = 255; // Alpha 
}; 

不過,我希望能夠找回自己的x和y位置。我想是這樣的:

for (var x = 0; x < imageData.width; x++) { 
    for (var y = 0; y < imageData.height; y++){ 
     var i = x * 4 + y * 4 * imageData.width; 
     if (i === 255) { 
      particles.push(new Particle(x, y); //Push a particle if the pixel is filled with any color 
     } 
    } 
} 

但不幸的是預期它不工作。我一直停留在這個相當長的一段時間,因此,所有的想法和建議更然後歡迎

回答

3

您可能想要量化像素以形成可放置粒子的網格(請參閱您鏈接的演示)。

爲此,您只需通過設置單個網格單元的寬度和高度來定義網格。然後,從每個網格角(或中心等)中選取一個像素來檢查是否有像素集。如果你這樣做,然後爲該位置創建一個粒子。

只是玩弄字體位置,字體大小和網格大小,以獲得視覺上令人愉快的結果。

請參見下面的代碼細節和演示:

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 
 
})
#canvas {background:#000}
<canvas id=canvas width=500 height=180></canvas>

+0

感謝,人,非常感謝! – 2014-11-06 17:34:51

+0

只是一個問題。我想設置一個功能,並在每2秒顯示一個英文字母的不同字母。我想我必須將像素操作放在函數中,並將其設置爲使用setInterval顯示不同的字母?你將如何繼續? – 2014-11-06 17:55:13

+0

沒問題!只需使用一個字符串,每次獲取一個字符並轉到下一個索引並進行渲染。我會建議你打開一個新的問題,你可以得到更詳細的答案。 – K3N 2014-11-07 01:25:36