html画布在悬停和显示信息时更改形状颜色

时间:2016-09-14 19:58:04

标签: javascript html css canvas

当光标悬停在项目上时,如何更改项目的颜色?我是通过函数随机生成圆圈数据的吗?我怎样才能显示一个简单的弹出窗口,显示有关该点的信息?

到目前为止,下面的代码将生成地图和所有点。

enter image description here

的index.html

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <meta name="description" content="The HTML5 Herald">
  <meta name="author" content="SitePoint">

  <link rel="stylesheet" href="css/style.css?v=1.0">
  <script src="js/script.js"></script>
</head>

<body>
    <canvas id="themap"></canvas>
</body>
</html>

的script.js

function Point(x, y, size) {
  this.x = x;
  this.y = y;
  this.size = size;
  this.name = "Doug"
}

function generate_points(){
  var points = new Array();

  for (i = 0; i < 100; i++) { 
    var radiusMin = 1;
    var radiusMax = 10;

    // calculate bounds of image/map
    var minX = 0;
    var maxX = 600;
    var minY = 0;
    var maxY = 400;

    var posX = Math.floor((Math.random() * maxX) + minX);
    var posY = Math.floor((Math.random() * maxY) + minY);

    var radius = Math.floor((Math.random() * radiusMax) + radiusMin);

    var pt = new Point(posX, posY, radius);
    points.push(pt);
  }
  return points;
}

window.onload = function(){     
    var canvas = document.getElementById("themap");
    canvas.width = 600;
    canvas.height = 400;

    var ctx = canvas.getContext('2d');
    var points = generate_points();
    trackTransforms(ctx);

  function redraw(){

        // Clear the entire canvas
        var p1 = ctx.transformedPoint(0,0);
        var p2 = ctx.transformedPoint(canvas.width,canvas.height);
        ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);

        ctx.save();
        ctx.setTransform(1,0,0,1,0,0);
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.restore();

        for (index = 0; index < points.length; ++index) {
          var pt = points[index];

          // console.log(a[index]);
          ctx.beginPath();
          ctx.lineWidth = 4;
          ctx.arc(pt.x, pt.y, pt.size, 0, 2*Math.PI);
          ctx.strokeStyle = "rgba(255, 0, 0, 0.5)";
          ctx.stroke();
          ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
          ctx.fill();
        }
      }
      redraw();

    var lastX=canvas.width/2, lastY=canvas.height/2;
};


function trackTransforms(ctx){
    var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
    var xform = svg.createSVGMatrix();
    ctx.getTransform = function(){ return xform; };

    var pt  = svg.createSVGPoint();
    ctx.transformedPoint = function(x,y){
        pt.x=x; pt.y=y;
        return pt.matrixTransform(xform.inverse());
    }
}

0 个答案:

没有答案