「労働者が自分の仕事をうまくやりたいなら、まず自分の道具を研ぎ澄まさなければなりません。」 - 孔子、「論語。陸霊公」
表紙 > プログラミング > Mousemoveでキャンバスからピクセルカラーを取得するにはどうすればよいですか?

Mousemoveでキャンバスからピクセルカラーを取得するにはどうすればよいですか?

2024 年 11 月 2 日に公開
ブラウズ:568

How to Get the Pixel Color from a Canvas on Mousemove?

Mousemove でキャンバスからピクセル カラーを取得する

概要

この投稿では、マウス移動中にマウス カーソルの下のピクセルの 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