使用canvas API可以创建多种应用,下面我做一个我特别感兴趣的例子,叫做热点图。
怎么理解热点图呢,其实很简单,就是度量温度的意思,可以用于任何可测量的活动。界面上活跃高的部分以用亮色标记,活跃低的用暗色标记。举个例子,热点图可以用在城市地图标记交通路况,或者在世界各地地图上上显示风暴的活动情况。
接下来这个例子是,鼠标移动到某个区域,会使某个区域的热度增加。如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>heatmap</title>
<style type="text/css">
#heatmap{
background-image:url(img/bac.jpg);
}
</style>
</head>
<body>
<h1>heatMap</h1>
<canvas id="heatmap" width="300" height="400"></canvas>
<button id='button'>清空画面</button>
</body>
<script type="text/javascript">
function log() {
console.log(arguments);
}
var points = {};
var SCALE = 3;
var x = -1;
var y = -1;
function loadDemo() {
document.getElementById("button").onclick = reset;
canvas = document.getElementById("heatmap");
context = canvas.getContext('2d');
context.globalAlpha = 0.2;
context.globalCompositeOperation = "lighter";
function sample() {
if (x != -1) {
addToPoint(x,y)
}
setTimeout(sample, 100);
}
canvas.onmousemove = function(e) {
x = e.clientX - e.target.offsetLeft;
y = e.clientY - e.target.offsetTop;
addToPoint(x,y)
}
sample();
}
function reset() {
points = {};
context.clearRect(0,0,300,400);
x = -1;
y = -1;
}
function getColor(intensity) {
var colors = ['#2F4F4F','#008000','#228B22','#32CD32','#00FF00','#7CFC00','#ADFF2F','#90EE90','yellow'];
return colors[Math.floor(intensity/2)];
}
function drawPoint(x, y, radius) {
context.fillStyle= getColor(radius);
radius = Math.sqrt(radius)*6;
context.beginPath();
context.arc(x, y, radius, 0, Math.PI*2, true)
context.closePath();
context.fill();
}
function addToPoint(x, y) {
x = Math.floor(x/SCALE);
y= Math.floor(y/SCALE);
if (!points[[x,y]]) {
points[[x,y]] = 1;
} else if (points[[x,y]]==10) {
return
} else {
points[[x,y]]++;
}
drawPoint(x*SCALE,y*SCALE, points[[x,y]]);
}
window.addEventListener("load", loadDemo, true);
</script>
</html>