假设有后端传来的数据:
data=
[
{H:1,V:3.7},
{H:1,V:6.3},
{H:1.1,V:5},
{H:2.2,V:3.56},
.....
]
通过js对数据进行简单转化后变为坐标信息,使用HTML5的CANVAS将其以点的形式画出来,结果大约是这个样子。
画出来没什么问题,但是还希望可以通过鼠标与各个点进行交互,鼠标滑过时可以获得当前点的所代表的原始{H,V}信息。
我尝试使用canvas的isPointInPath(x,y),可以获得交互状态,但是无法具体到某一个点。
请问这个是否有人有比较好的实现方式?
2014-08-01 09:47:07 lawine9 楼主
8个回答
给一个实例代码<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<script type="text/javascript">
var list = [];
var currentC;
var _e={};
var cricle = function(x,y,r){
this.x=x;
this.y=y;
this.r=r;
this.isCurrent=false;
this.drawC=function(ctx,x,y){
ctx.save();
ctx.beginPath();
ctx.moveTo(this.x,this.y-this.r);
ctx.arc(this.x,this.y,this.r,2*Math.PI,0,true);
if((x && y && ctx.isPointInPath(x, y) && !currentC )||this.isCurrent) {
ctx.fillStyle = '#ff0000';
currentC = this;
this.isCurrent = true;
}else{
ctx.fillStyle = '#999999';
}
ctx.fill();
}
}
function draw(){
var canvas = document.getElementById('tutorial');
if(canvas.getContext){
var ctx = canvas.getContext('2d');
for(var i=0;i<10;i++){
var x = Math.random()*100;
var y = Math.random()*100;
var c = new cricle(x,y,5);
c.drawC(ctx);
list.push(c);
}
}
}
function reDraw(e){
e = e || event;
var canvas = document.getElementById('tutorial');
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
canvas.width = canvas.width;
if(canvas.getContext){
var ctx = canvas.getContext('2d');
for(var i=0;i<list.length;i++){
var c = list[i];
c.drawC(ctx,x,y);
}
}
}
function show(e){
e = e || event;
var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
if(currentC){
currentC.x = parseInt(x+(x-currentC.x)/5);
currentC.y = parseInt(y+(y-currentC.y)/5);
document.getElementById('info').innerHTML = 'X:' + currentC.x +' Y:' + currentC.y;
}
_e = e;
}
window.onload = function(){
var canvas = document.getElementById('tutorial');
draw();
canvas.onmousedown = function(e){
e = e || event;
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
if(currentC) currentC.isCurrent = false;
currentC = null;
reDraw(e);
_e=e;
var showTimer = setInterval(function(e){
reDraw(e);
},10,_e);
canvas.onmousemove = show;
document.onmouseup=function(){
if(currentC) currentC.isCurrent=false;
currentC = null;
canvas.onmousemove = null;
clearInterval(showTimer);
}
}
}
</script>
<style type="text/css">
canvas { border: 1px solid black; }
</style>
</head>
<body style="background:#eeeeee;">
<canvas id="tutorial" width="400" height="200" style="z-index:100;display:block;position:absolute;"></canvas>
<span id=info></span>
</body>
</html>
2014-08-01 10:52:38 xuzuning 5楼
交互的话,把这些点转换成元素放在DIV里好些吧
HTML5我了解的也不多,不过感觉貌似还没有跟canvas交互的好办法
2014-08-01 09:57:19 liuxing19870629 1楼