ColorPicker implementation using JavaScript and Canvas(使用 JavaScript 和 Canvas 实现 ColorPicker)
问题描述
我尝试使用 Canvas 实现 ColorPicker 只是为了好玩.但我似乎迷路了.因为我的浏览器由于所有这些 for 循环而在加载时冻结了一段时间.我正在添加此脚本结果的屏幕截图:
I'm trying to implement ColorPicker using Canvas just for fun. But i seem lost. as my browser is freezing for a while when it loads due to all these for loops.
I'm adding the screenshot of the result of this script:
目前,我只想用更好的算法解决冻结问题,并且不显示黑色和灰色.请有人帮助我.
Currently , i only want a solution about the freezing problem with better algorithm and it's not displaying the BLACK and GREY colors. Please someone help me.
推荐答案
如果要获取鼠标下像素的rgba,必须使用context.getImageData.
If you want to fetch the rgba of the pixel under the mouse, you must use context.getImageData.
getImageData 返回一个像素数组.
getImageData returns an array of pixels.
var pixeldata=context.getImageData(0,0,canvas.width,canvas.height);
每个像素由 4 个连续的数组元素定义.
Each pixel is defined by 4 sequential array elements.
所以如果你用 getImageData 得到了一个像素数组:
So if you have gotten a pixel array with getImageData:
// first pixel defined by the first 4 pixel array elements
pixeldata[0] = red component of pixel#1
pixeldata[1] = green component of pixel#1
pixeldata[2] = blue component of pixel#1
pixeldata[4] = alpha (opacity) component of pixel#1
// second pixel defined by the next 4 pixel array elements
pixeldata[5] = red component of pixel#2
pixeldata[6] = green component of pixel#2
pixeldata[7] = blue component of pixel#2
pixeldata[8] = alpha (opacity) component of pixel#2
所以如果你有一个 mouseX 和 mouseY 那么你可以像这样获得鼠标下的 r,g,b,a 值:
So if you have a mouseX and mouseY then you can get the r,g,b,a values under the mouse like this:
// get the offset in the array where mouseX,mouseY begin
var offset=(imageWidth*mouseY+mouseX)*4;
// read the red,blue,green and alpha values of that pixel
var red = pixeldata[offset];
var green = pixeldata[offset+1];
var blue = pixeldata[offset+2];
var alpha = pixeldata[offset+3];
这是一个在画布上绘制色轮并在鼠标下显示 RGBA 的演示:
Here's a demo that draws a colorwheel on the canvas and displays the RGBA under the mouse:
http://jsfiddle.net/m1erickson/94BAQ/
这篇关于使用 JavaScript 和 Canvas 实现 ColorPicker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JavaScript 和 Canvas 实现 ColorPicker


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01