HTML5 <canvas> 标签是用于绘制图像,不过,<canvas> 元素本身并没有绘制能力(它仅仅是图形的容器),必须使用脚本(通常是 JS)来完成实际的绘图任务。

<canvas>是有兼容性的,Internet Explorer 9、Firefox、Opera、Chrome 以及 Safari 支持 <canvas> 及其属性和方法。(注释:Internet Explorer 8 以及更早的版本不支持 <canvas> 元素。)

好了,其他不多说了,直接上代码。

演示地址

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> canvas{ border: 1px solid red; } #block{ display: inline-block; width: 50px; height: 50px; vertical-align: top; border: 1px solid red; } </style> </head> <body> <canvas id="canvas" width="400px" height="400px"></canvas> <span id="block"></span> <script> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); for(var i = 0;i<16;i++){ for(var j =0;j<16;j++){ ctx.fillStyle = "rgb(0,"+(255-i*16)+","+(255-j*16)+")"; ctx.fillRect(i*25,j*25,25,25); } } canvas.onmousemove = function(e){ var e = e || window.event; var x = e.layerX; var y = e.layerY; 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>