html5 访问像素值 (拾色器)
1 <div class="wrap"> 2 <canvas id="myCanvas" width="500" height="500"></canvas> 3 </div>
1 function draw(id){ 2 var canvas = document.getElementById(id); 3 if(canvas == null){ 4 return false; 5 } 6 var context = canvas.getContext("2d"); 7 var img = new Image(); 8 img.src = 'heng.jpg'; 9 img.onload = function(){ 10 context.drawImage(img,0,0,500,500); 11 }; 12 13 canvas.onclick = function(e){ 14 var canvasX = Math.floor(e.pageX - canvas.offsetLeft);// 向下舍 15 var canvasY = Math.floor(e.pageY - canvas.offsetTop); 16 17 var imageData = context.getImageData(canvasX, canvasY, 1,1);// 获取点击的那一点的坐标 18 var pixel = imageData.data; 19 var pixelColor = "rgba("+ pixel[0] + ", " + pixel[1] +", "+ pixel[2] +", " + pixel[3] +")"; 20 21 console.log(pixelColor); 22 document.body.style.background = pixelColor; 23 }; 24 } 25 26 draw("myCanvas");
其中有点不明白,alpha的值不是0-1,为什么我访问pixe[3]得到的是255呢?
疯癫不成狂,有酒勿可尝;世间良辰美,终成水墨白。