Canvas 熱點圖
阿新 • • 發佈:2019-01-28
window.onload=function(){
var timer=null;
var points={};
var x=-1;
var y=-1;
var scale=3;//縮放比例
var canvas=document.getElementById('canvas');
var reset=document.getElementById('reset');
var cxt=canvas.getContext('2d');
cxt.globalAlpha=0.2;
cxt.globalCompositeOperation='lighter' ;
var timer=null;
var sample=function(){
if(x>0 && x<300){
addPoint(x,y);
}
timer=setTimeout(sample,100);//用來迴圈
}
var addPoint=function(x,y){
//計算熱度值
if(!points[[x,y]]){
points[[x,y]]=1;
}else{
if(points[[x,y]]<10){
points[[x,y]]+=1 ;
}
}
drawPoint(x,y,points[[x,y]]);
}
//畫圓 熱度值越大,半徑越大,顏色越深
var drawPoint=function(x,y,scale){
var colors=['#e072933','#2e4045','#8c593b','#b2814e','#fac268','#fad237'];
var num=Math.floor(scale/2);
cxt.beginPath();
cxt.arc(x,y,scale*3,0,360,false);
cxt.closePath();
cxt.fillStyle=colors[num];
cxt.fill();console.log(scale);
}
canvas.onmousemove=function (event){
if(timer==null){
timer=setTimeout(sample,10);
}
var event=window.event||ev;
x=event.clientX-this.offsetLeft;
y=event.clientY-this.offsetTop;
addPoint(x,y);
}
canvas.onmouseout=function(){
clearTimeout(timer);
timer=null;
}
reset.onclick=function(){
points={};
x=-1;y=-1;
cxt.clearRect(0,0,300,300);
}
sample();
}