在设置颜色时有多种方法:
采用颜色的英文单词 比如 red 指红色
采用#号,后面跟6位的16进制数字,比如:#ff0000 表示红色 每个数字的取值为0~9,a~f(a表示10,f表示15)。当第1~2位、第3~4位、第5~6位的数字分别相同时,可以缩写为3位,如 #ff0000可以缩写为 #f00, #3399ff可以缩写为#39f。对于#3699ff此类不满足条件的颜色值则不能缩写
采用rgb数值表示法,比如 rgb(255, 0, 0)表示红色,三个数字分别表示红、绿、蓝,取值范围为0~255
采用rgba数值表示法,比如rgba(255, 0, 0, 0.5)表示50%透明度的红色,最后一个数字表示透明度,取值为0~1之间的小数,0表示全透明,1表示不透明。
HTML5 简单的颜色选取器
<!DOCTYPE html><html lang="zh">
<head>
<meta charset="gbk" />
<title>Canvas Example 4 (Detecting Colors)</title>
<script>
window.onload = function () {
//获取页面DOM元素
var preview = document.getElementById('preview')
var r = document.getElementById('r')
var g = document.getElementById('g')
var b = document.getElementById('b')
var a = document.getElementById('a')
var mx = document.getElementById('mx')
var my = document.getElementById('my')
var canvas = document.getElementById('myCanvas')
//绑定鼠标移动事件
canvas.addEventListener('mousemove', move, false)
var c = canvas.getContext('2d')
var building = new Image()
building.src = "cinema.png"//加载图片
building.onload=draw
function draw () {
c.drawImage(building, 0, 0, canvas.width, canvas.height)
}
function move (e) {
//在页面显示鼠标相对于窗口的坐标
mx.innerHTML = e.clientX
my.innerHTML = e.clientY
//获取图像数据
var img = c.getImageData(e.clientX, e.clientY, 1, 1)
var idata = img.data
//获取像素值
var red = idata[0]
var green = idata[1]
var blue = idata[2]
var alpha = idata[3]
//在页面显示像素的R,G,B,A值
r.innerHTML = red
g.innerHTML = green
b.innerHTML = blue
a.innerHTML = (alpha > 0) ? alpha : 'Transparent'
preview.style.backgroundColor = 'rgba(' + red + ', ' + green + ', ' + blue + ', ' + alpha + ')'
}
}
</script>
<style type="text/css" media="screen">
body { margin: 0px padding: 0px }
canvas {
border: 1px solid black
float: left
}
ul {
list-style: none
margin: 10px 10px 10px 10px
padding: 0px
float: left
}
ul li { font-weight: bold }
ul li span { font-weight: normal }
ul li #preview { width: 50px height: 50px border: 1px solid black }
</style>
</head>
<body>
<canvas id="myCanvas" width="300" height="300">
Your browser doesn't include support for the canvas tag.
</canvas>
<ul>
<li><div id="preview"></div></li>
<li>Red: <span id="r">NULL</span></li>
<li>Green: <span id="g">NULL</span></li>
<li>Blue: <span id="b">NULL</span></li>
<li>Alpha: <span id="a">NULL</span></li>
<li>Mouse X: <span id="mx">NULL</span></li>
<li>Mouse Y: <span id="my">NULL</span></li>
</ul>
</body>
</html>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)