在鼠标悬停时从画布获取像素颜色

在鼠标悬停时从画布获取像素颜色,第1张

在鼠标悬停时从画布获取像素颜色

这是一个完整的,独立的示例。首先,使用以下HTML:

<canvas id="example" width="200" height="60"></canvas><div id="status"></div>

相关的Javascript:

// set up some sample squaresvar example = document.getElementById('example');var context = example.getContext('2d');context.fillStyle = "rgb(255,0,0)";context.fillRect(0, 0, 50, 50);context.fillStyle = "rgb(0,0,255)";context.fillRect(55, 0, 50, 50);$('#example').mousemove(function(e) {    var pos = findPos(this);    var x = e.pageX - pos.x;    var y = e.pageY - pos.y;    var coord = "x=" + x + ", y=" + y;    var c = this.getContext('2d');    var p = c.getImageData(x, y, 1, 1).data;     var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);    $('#status').html(coord + "<br>" + hex);});

上面的代码假定存在jQuery和以下实用程序功能:

function findPos(obj) {    var 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);}// set up some sample squaresvar example = document.getElementById('example');var context = example.getContext('2d');context.fillStyle = "rgb(255,0,0)";context.fillRect(0, 0, 50, 50);context.fillStyle = "rgb(0,0,255)";context.fillRect(55, 0, 50, 50);$('#example').mousemove(function(e) {    var pos = findPos(this);    var x = e.pageX - pos.x;    var y = e.pageY - pos.y;    var coord = "x=" + x + ", y=" + y;    var c = this.getContext('2d');    var p = c.getImageData(x, y, 1, 1).data;    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);    $('#status').html(coord + "<br>" + hex);});function findPos(obj) {    var 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);}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><canvas id="example" width="200" height="60"></canvas><div id="status"></div>


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5509200.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存