この投稿では、マウス移動中にマウス カーソルの下のピクセルの RGB 値を取得する方法を説明します。キャンバス要素上を移動します。自己完結型の例を使用して包括的なアプローチを提供します。
これを実現するには、まず目的のサイズのキャンバスを作成します:
正方形などの要素でキャンバスを塗りつぶします:
const example = document.getElementById('example');
const ctx = example.getContext('2d');
ctx.fillStyle = randomColor();
ctx.fillRect(0, 0, 50, 50);
ctx.fillStyle = randomColor();
ctx.fillRect(55, 0, 50, 50);
ctx.fillStyle = randomColor();
ctx.fillRect(110, 0, 50, 50);
最後に、カーソルの位置のピクセル値をキャプチャする Mousemove イベント ハンドラーを追加します。
$('#example').mousemove(function(e) {
// Calculate the position relative to the canvas
const pos = findPos(this);
const x = e.pageX - pos.x;
const y = e.pageY - pos.y;
const coord = `x=${x}, y=${y}`;
// Get the pixel value
const c = this.getContext('2d');
const p = c.getImageData(x, y, 1, 1).data;
// Convert to hex format
const hex = "#" ("000000" rgbToHex(p[0], p[1], p[2])).slice(-6);
// Display the color information
$('#status').html(coord "
" hex);
});
このコードは、要素の位置を検索し、RGB 値を 16 進数に変換するためのサポート関数に依存しています。これらの関数を次のように定義します。
function findPos(obj) {
let curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255) throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
function randomInt(max) {
return Math.floor(Math.random() * max);
}
function randomColor() {
return `rgb(${randomInt(256)}, ${randomInt(256)}, ${randomInt(256)})`;
}
動作中の完全な例を確認するには、次のリンクにアクセスしてください:
https://bl.ocks.org/wayneburkett/ca41a5245a9f48766b7bc881448f9203
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3