html5 学习简单的拾色器

时间:2021-05-08

下面是源码 需要浏览器支持html5

复制代码代码如下:
<html>
<head>
</head>
<body>
<canvas id="colorPicker" onmousemove="showCurrentColor(event)">
</canvas>
<br/>
<div id="textResult">
</div>
<script type="text/javascript">
if(document.createElement("canvas")){
if(document.getElementById("colorPicker").getContext){
var can = document.getElementById("colorPicker");
can.setAttribute("height",300);
var cxt = can.getContext("2d");
var gradient = cxt.createLinearGradient(0.5,0.5,0,150);
gradient.addColorStop(0,'#00ff00');
gradient.addColorStop(1,'#ff0000');
cxt.fillStyle=gradient;
cxt.fillRect(0,0,60,200);
var ox= can.offsetLeft
var oy = can.offsetTop;
var span = document.createElement("input");
span.setAttribute("id","rgba");
document.getElementById("textResult").appendChild(span);
}
}
function showCurrentColor(e){
var x = e.clientX - 8;
var y = e.clientY - 29;
var w = 10;
if(document.createElement("canvas")){
if(document.getElementById("colorPicker").getContext){
var can = document.getElementById("colorPicker");
var cxt = can.getContext("2d");
var gradient = cxt.createLinearGradient(0.5,0.5,0,150);
var span = document.getElementById("rgba");
var imgDatas = cxt.getImageData(ox,oy,10,200);
var imgData = imgDatas.data;
var g = imgData[4 *(w)*(y)+(x)*4 + 1];
var r = imgData[4 *(w)*(y)+(x)*4];
var b = imgData[4 *(w)*(y)+(x)*4 + 2];
var a = imgData[4 *(w)*(y)+(x)*4 + 3];
span.value="r="+r+" g="+ g+" b="+b +" a="+a;
document.getElementById("textResult").appendChild(span);
}
}
}
</script>
</body>
</html>

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章