首先声明:这个代码案例来源于:
https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas#%E7%BC%A9%E6%94%BE%E5%92%8C%E5%8F%8D%E9%94%AF%E9%BD%BF
不过其中代码运行出现一些问题。自己做了修改后完成。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas-像素操作</title>
</head>
<body>
<canvas id="canvas" width="300" height="227"></canvas>
<canvas id="canvas2" width="300" height="200"></canvas>
<canvas id="canvas3" width="300" height="200"></canvas>
</body>
<script>
/*
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();// 创建一个<img>元素
img.crossOrigin='anonymous';
img.src='./rhino.jpg';
img.οnlοad=function(){
ctx.drawImage(img,0,0);
img.style.display='none';
};
canvas.addEventListener('click',function(e){
var x=e.offsetX;
var y=e.offsetY;
console.log(ctx.getImageData(100,150,5,5));
console.log(ctx.getImageData(x,y,1,1).data);
});
*/
var img=new Image();
img.src='./color.jpg';
img.crossOrigin='anonymous';//这行代码很重要;
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
img.onload=function(){
ctx.drawImage(img,0,0);
img.style.display='none';
};
var hoveredColor=document.getElementById('canvas2');
var selectedColor=document.getElementById('canvas3');
function pick(event,destination){
var x=event.layerX;//鼠标的x,y数值;
var y=event.layerY;
console.log('mouse position of x,y is ',x,y);
var pixel=ctx.getImageData(x,y,1,1);
var data=pixel.data;
//console.log('pixel is =',pixel);
//var data=pixel.data;
console.log('data is equal to ',data);
const rgba='rgba('+data[0]+','+data[1]+','+data[2]+','+data[3]/255+')';
console.log('rgba= ',rgba);
destination.style.background=rgba;
destination.getContext('2d').font="24px serif";
destination.getContext('2d').strokeText(rgba,10,100);
return rgba;
}
canvas.addEventListener('mousemove',function(event){
hoveredColor.getContext('2d').clearRect(0,0,300,200);
pick(event,hoveredColor);
});
canvas.addEventListener('click',function(event){
selectedColor.getContext('2d').clearRect(0,0,300,200);
pick(event,selectedColor);
});
</script>
</html>
给出结果:(自己做了修改后,每次颜色输出都会把原来地清除;)