用photoshop创建了一个10px*5px的图片,背景色设置为rgb(2,8,10),保存为t.png,使用js代码获取图片数据,打印的数据对象与循环遍历的值不同,
js:
> function createGSCanvas(img) { > > var canvas=document.createElement("canvas"); > canvas.width=img.width; > canvas.height=img.height; > var ctx=canvas.getContext("2d"); > ctx.drawImage(img,0,0); > > var c = ctx.getImageData(0, 0, img.width, img.height); > > console.log(c); > > for (i=0; i<c.height; i++) { > for (j=0; j<c.width; j++) { > var x = (i*4) * c.width + (j*4); > var r = c.data[x]; > console.log(r); > var g = c.data[x+1]; > console.log(g); > var b = c.data[x+2]; > console.log(b); > c.data[x] = c.data[x+1] = c.data[x+2] = (r+g+b)/3; > } > } > ctx.putImageData(c,0,0,0,0, c.width, c.height); > return canvas.toDataURL(); } > > window.onload = function() { > createGSCanvas(document.getElementById('avatar')); }
html:
<img src="t.png" id="avatar" >
截图如下:
请大神帮忙解惑,万分感谢,为何打印整体数据对象 与 循环打印数组中的每个颜色值 不同