最近看到一个颜色选择网站,网站地址点这里。觉得很有趣,想自己实现一下,顺便学习一下canvas。
没有看源码,全部是自己设计的,预计两天完成吧
思路和实现
调色盘的实现
使用canvas画一个渐变色画布,其中x轴是色度,y轴是明暗度,官网其实还有一个z轴,是鼠标滚动选择饱和度,这里先不考虑。
-
首先,先做x轴的色盘,相当于做一个类似ps里的选色的彩虹条,思路是创建canvas的渐变对象,从左到右分为六份,是红黄绿青蓝紫这六种颜色,最后又过渡回到红色做一个,代码如下:
<canvas class="box" id="show" width="500px" height="500px"></canvas>
.box { position: relative; background-color: pink; margin: 100px; }
var show = document.getElementById("show"); if (show.getContext) { //首先判断getcontext方法是否存在,这是一个良好的习惯 var context = show.getContext('2d'); var gradientBar = context.createLinearGradient(0, show.width, show.width, show.width);//创建渐变,前两个参数是渐变开始的横纵坐标,后两个参数是渐变结束的横纵坐标 gradientBar.addColorStop(0, '#f00'); gradientBar.addColorStop(1 / 6, '#f0f'); gradientBar.addColorStop(2 / 6, '#00f'); gradientBar.addColorStop(3 / 6, '#0ff'); gradientBar.addColorStop(4 / 6, '#0f0'); gradientBar.addColorStop(5 / 6, '#ff0'); gradientBar.addColorStop(1, '#f00'); context.fillStyle = gradientBar; context.fillRect(0, 0, show.width, show.width); }
效果:
== 这里有个小问题是,我发现在class里给canvas设置宽高没有用,只能在canvas标签里专门设置一下,大家注意一下这个问题 ==
-
我利用白色过渡到透明再过渡到黑色来做明度的过渡,有其他更好的方法可以在评论区讨论哦
在js代码中加入://白色透明黑色,明暗度实现 var lightToDark = context.createLinearGradient(0, 0, 0, show.width); lightToDark.addColorStop(0, "#fff"); lightToDark.addColorStop(1 / 2, 'rgba(255,255,255,0)'); lightToDark.addColorStop(1, '#000'); context.fillStyle = lightToDark; context.fillRect(0, 0, show.width, show.width);
效果:
实现鼠标滑动到不同的位置,获取对应位置的rgb颜色
- 利用addEventListener监听鼠标滑动,并获得鼠标的位置
- 利用canvas的getImageData() 方法获得当前位置的颜色
- 创建一个小方格来跟随选择颜色
<canvas class="box" id="show" width="500px" height="500px"></canvas>
<em id="cur"></em>
.box {
position: relative;
background-color: pink;
margin: 100px;
}
/* 选择颜色的小方格 */
#cur {
width: 3px;
height: 3px;
outline: 2px solid #535353;
margin-left: -1px;
margin-top: -1px;
position: absolute;
}
show.addEventListener('mouseover', function (e) {
var ePos = {
x: e.layerX || e.offsetX,
y: e.layerY || e.offsetY
}
//前两个参数为鼠标的位置,后娘个参数为canvas的宽高
var imgData = context.getImageData(ePos.x, ePos.y, show.width, show.height).data;
//可以通过下面的方法获得当前的rgb值
var red = imgData[0];
var green = imgData[1];
var blue = imgData[2];
var rgbStr = "rgb(" + red + "," + green + ',' + blue + ")";
console.log(rgbStr);
cover.style.backgroundColor = rgbStr;
document.onmousemove = function (e) {
var pos = {
x: e.clientX,
y: e.clientY
}
cur.style.left = pos.x &#