在项目当中,要实现某业务需求例如PS魔棒功能时,则需要获取点击坐标的颜色信息。
功能不复杂,代码也很少,一看便知~~
核心API为getImageData,传入4个参数,前2个为点击坐标xy,后2个都传1;表示以当前点击位置为起点,取宽为1、高为1的像素范围信息;
<html>
<style>
.box {
display: flex;
}
#c {
border: 1px solid rgb(0, 0, 0);
}
.color {
width: 40px;
height: 40px;
border: 1px solid red;
}
</style>
<body>
<div class="box">
<canvas id="c" width="200" height="200"></canvas>
<div>点击的颜色:</div>
<div class="color"></div>
</div>
<script>
c.width = 200;
c.height = 200;
var ctx = c.getContext("2d");
var gr = ctx.createLinearGradient(0, 0, 300, 0);
gr.addColorStop(0, "#fff");
gr.addColorStop(0.15, "#8B00FF");
gr.addColorStop(0.25, "#0000FF");
gr.addColorStop(0.35, "#00FFFF");
gr.addColorStop(0.45, "#00FF00");
gr.addColorStop(0.55, "#FFFF00");
gr.addColorStop(0.65, "#FF7F00");
gr.addColorStop(0.75, "#FF0000");
gr.addColorStop(1, "#fff");
ctx.fillStyle = gr;
ctx.fillRect(0, 0, 200, 200);
c.onmousedown = function (e) {
console.log(e.offsetX, e.offsetY);
const imageData = ctx.getImageData(e.offsetX, e.offsetY, 1, 1);
console.log(imageData);
const pixelData = imageData.data;
const color = `rgba(${pixelData[0]}, ${pixelData[1]}, ${pixelData[2]}, ${pixelData[3]})`;
let el = document.getElementsByClassName('color')[0]
el.style.background = color;
};
</script>
</body>
</html>