你的位置:首页 > 网页设计

[网页设计]HTML5、canvas颜色拾取器


 效果图:

代码:

<!doctype html><html lang="en"><head>  <meta charset="UTF-8" />  <title>canvas 颜色拾取器</title>  <style>    #canvas {      border: 1px solid red;    }    #block {      display: inline-block;      width:50px;      height: 50px;      vertical-align: top;      background-color: black;    }  </style></head><body>    <canvas id="canvas" width="400" height="400">你的浏览器不支持canvas</canvas>  <span id="block"></span>  <script>    //获取id     var canvas = document.getElementById("canvas");    var ctx = canvas.getContext("2d");    //绘制填充颜色块     for(var i = 0; i < 16; i++) {      for(var j = 0; j < 16; j++) {        // gba(255,255,0) --->gba(255,0,0)        ctx.fillStyle = "rgb("+(255 - j*16)+","+(255 - i*16)+",0)";        ctx.fillRect(i*25,j*25,25,25);      }    }    // 显示获取的颜色    var block = document.getElementById("block");    // 点击利用imgDate获取rgb值    canvas.onclick = function(e) {      var e = e || window.event;      //e.layerX,e.layerY相对于绑定事件对象canvas的坐标      var x = e.layerX;      var y = e.layerY;      // console.log(e);      var imgData = ctx.getImageData(x,y,1,1);      var r = imgData.data[0];      var g = imgData.data[1];      var b = imgData.data[2];            block.style.backgroundColor = "rgb("+r+","+g+","+b+")";    }  </script></body></html>