使用 JavaScript 和 Canvas 实现 ColorPicker [英] ColorPicker implementation using JavaScript and Canvas

查看:12
本文介绍了使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆