HTML5 canvas熱點圖應用
使用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>