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

查看:93
本文介绍了使用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天全站免登陆