यह पोस्ट बताती है कि आप माउस कर्सर के नीचे पिक्सेल के आरजीबी मान कैसे प्राप्त कर सकते हैं एक कैनवास तत्व पर आगे बढ़ना। हम एक स्व-निहित उदाहरण के साथ एक व्यापक दृष्टिकोण प्रदान करेंगे।
इसे प्राप्त करने के लिए, पहले वांछित आयामों के साथ एक कैनवास बनाएं:
कैनवास को वर्गों जैसे तत्वों से भरें:
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);
अंत में, माउसमूव ईवेंट हैंडलर जोड़ें जो कर्सर की स्थिति पर पिक्सेल मान कैप्चर करता है:
$('#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);
});
यह कोड तत्व की स्थिति खोजने और आरजीबी मानों को हेक्स में परिवर्तित करने के लिए सहायक कार्यों पर निर्भर करता है। इन फ़ंक्शन को इस प्रकार परिभाषित करें:
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