<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>像素操作</title>
<style>
canvas {
border: 1px solid red;
}
</style>
</head>
<body>
<canvas width="400" height="200" id="canvas"></canvas>
<script>
window.onload = function () {
let canvas = document.querySelector('#canvas');
if (!canvas.getContext) return;
let ctx = canvas.getContext('2d');
ctx.save();
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.fillRect(200, 0, 100, 100);
ctx.fill();
ctx.restore();
let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
let color = getPxColor(imageData, 250, 80);
console.log(color);
function getPxColor(imageData, x, y) {
let color = [];
// 有多宽,就是一排有多少个像素点
let width = imageData.width;
for (let i = 0; i < imageData.data.length; i++) {
color[0] = imageData.data[(y * width + x) * 4];
color[1] = imageData.data[(y * width + x) * 4 + 1];
color[2] = imageData.data[(y * width + x) * 4 + 2];
color[3] = imageData.data[(y * width + x) * 4 + 3];
}
return color;
}
}
</script>
</body>
</html>
获取画布上的任意一个坐标对应的像素点的颜色值
最新推荐文章于 2024-04-01 16:53:00 发布