在图像上绘制对象并拖动图像

时间:2013-04-01 15:48:23

标签: jquery html5 canvas html5-canvas

我有一张像小地图的图像。我想做一些像 1.像http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-an-image-tutorial/一样拖动它 2.在图像上绘制一些对象(如:线,点)(图像拖动时附加图像的对象)
我尝试做一些事情,比如使用http://www.html5canvastutorials.com/kineticjs/html5-canvas-kineticjs-label-tutorial/等。但是当我拖动图像时它没有附加图像。

2 个答案:

答案 0 :(得分:0)

您必须在画布上跟踪mousedown和mouseup事件。

  • 在mousedown上获取鼠标坐标,使它们相对于画布,测试它们是否在画布上绘制的图像内(点对点)。
  • 如果鼠标位于图像内:在mouseup上,根据mousedown坐标和mouseup坐标之间的差值重绘画布上的图像。

答案 1 :(得分:0)

我看到你正在看KineticJS的例子。

以下是如何在KineticJS中执行地图加点和线的示例。使用这个库可能比开始使用起来更简单,而不是单独学习在画布中拖动的复杂性。

在此示例代码中,请确保将URL放入地图而不是img1.src =“yourMap.jpg”。

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {margin: 0px;padding: 0px;}
      canvas{border:1px solid red;}
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.4.0.min.js"></script>
    <script>

      var stage = new Kinetic.Stage({
        container: 'container',
        width: 500,
        height: 500
      });
      var layer = new Kinetic.Layer();

      var img1=new Image();
      img1.onload=function(){
          createDragMap();
      }
      img1.src="yourMap.jpg";

      function createDragMap(){

            var map = new Kinetic.Shape({
              drawFunc: function(canvas) {
                var context = canvas.getContext();

                // draw the map and a border around the map
                context.drawImage(img1,0,0);
                context.beginPath();
                context.rect(0,0,img1.width,img1.height);
                context.stroke(this);

                // add your points to the map here
                // for example...
                context.rect(23,67, 4,4);          
                context.rect(153,87, 4,4); 
                context.moveTo(23,67);
                context.lineTo(153,87);         

                // fill and stroke must be done last!
                canvas.fillStroke(this);
              },
              width: img1.width,
              height: img1.height,
              stroke:"blue",
              strokeWidth: 2,
              draggable:true
            });
            layer.add(map);
            stage.add(layer);
      }
    </script>
  </body>
</html>