【问题标题】:How to get the position(in coordinates) of any image element(resizable/draggable) drawn upon html5 canvas?如何获取在 html5 画布上绘制的任何图像元素(可调整大小/可拖动)的位置(坐标)?
【发布时间】:2013-04-07 09:13:29
【问题描述】:

目前我在 html5 画布上绘制图像,点击该图像。绘制该图像的代码如下:

这是给定的脚本函数:

<script>
  function update(activeAnchor) {
    var group = activeAnchor.getParent();

    var topLeft = group.get('.topLeft')[0];
    var topRight = group.get('.topRight')[0];
    var bottomRight = group.get('.bottomRight')[0];
    var bottomLeft = group.get('.bottomLeft')[0];
    var image = group.get('.image')[0];

    var anchorX = activeAnchor.getX();
    var anchorY = activeAnchor.getY();

    // update anchor positions
    switch (activeAnchor.getName()) {
      case 'topLeft':
        topRight.setY(anchorY);
        bottomLeft.setX(anchorX);
        break;
      case 'topRight':
        topLeft.setY(anchorY);
        bottomRight.setX(anchorX);
        break;
      case 'bottomRight':
        bottomLeft.setY(anchorY);
        topRight.setX(anchorX); 
        break;
      case 'bottomLeft':
        bottomRight.setY(anchorY);
        topLeft.setX(anchorX); 
        break;
    }

    image.setPosition(topLeft.getPosition());

    var width = topRight.getX() - topLeft.getX();
    var height = bottomLeft.getY() - topLeft.getY();
    if(width && height) {
      image.setSize(width, height);
    }
  }

  function addAnchor(group, x, y, name) {
    var stage = group.getStage();
    var layer = group.getLayer();

    var anchor = new Kinetic.Circle({
      x: x,
      y: y,
      stroke: '#666',
      fill: '#ddd',
      strokeWidth: 2,
      radius: 8,
      name: name,
      draggable: true,
      dragOnTop: false
    });

    anchor.on('dragmove', function() {
      update(this);
      layer.draw();
    });
    anchor.on('mousedown touchstart', function() {
      group.setDraggable(false);
      this.moveToTop();
    });
    anchor.on('dragend', function() {
      group.setDraggable(true);
      layer.draw();
    });
    // add hover styling
    anchor.on('mouseover', function() {
      var layer = this.getLayer();
      document.body.style.cursor = 'pointer';
      this.setStrokeWidth(4);
      layer.draw();
    });
    anchor.on('mouseout', function() {
      var layer = this.getLayer();
      document.body.style.cursor = 'default';
      this.setStrokeWidth(2);
      layer.draw();
    });

    group.add(anchor);
  }

  function loadImages(sources, callback) {
    var images = {};
    var loadedImages = 0;
    var numImages = 0;
    for(var src in sources) {
      numImages++;
    }
    for(var src in sources) {
      images[src] = new Image();
      images[src].onload = function() {
        if(++loadedImages >= numImages) {
          callback(images);
        }
      };
      images[src].src = sources[src];
    }
  }

  function initStage(images) {
    var stage = new Kinetic.Stage({
      container: 'container_canvas',
      width: 578,
      height: 400
    });
    var darthVaderGroup = new Kinetic.Group({
      x: 270,
      y: 100,
      draggable: true
    });

    var layer = new Kinetic.Layer();


    layer.add(darthVaderGroup);

    stage.add(layer);


    var darthVaderImg = new Kinetic.Image({
      x: 0,
      y: 0,
      image: images.darthVader,
      width: 200,
      height: 138,
      name: 'image'
    });

    darthVaderGroup.add(darthVaderImg);
    addAnchor(darthVaderGroup, 0, 0, 'topLeft');
    addAnchor(darthVaderGroup, 200, 0, 'topRight');
    addAnchor(darthVaderGroup, 200, 138, 'bottomRight');
    addAnchor(darthVaderGroup, 0, 138, 'bottomLeft');

    darthVaderGroup.on('dragstart', function() {
      this.moveToTop();
    });
    stage.draw();

  }
function putDesign(designSrc)
{
designSrc = designSrc.split("images/"); 
 var sources = {
    darthVader: 'images/'+designSrc[1],
  };
  loadImages(sources, initStage);
  }
</script>

我正在为此使用 kinetic-v4.4.0.min.js (http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.4.0.min.js), 在 html 中我只是调用这个函数 putDesign ,所以这段代码将在这个 iv 中绘制一个画布。

    <div class="behind" id="behind"> 
        <div id="canvasProductImage" style="text-align:center; width:300px;    height:300px; background:url(images/a.png) 100px 100px  no-repeat;">

       <div id="container_canvas"></div>
        </div> 

现在这段代码将使我在 div 中绘制图像。这里是图像 1(tshirt(我们将在其中绘制画布的 div 的背景图像))和图像 2(绘制的元素), 所以主要任务是我如何获得drwan图像的位置,这意味着我将如何知道画布上绘制的图像在坐标中的位置?由于图像对象可调整大小和可拖动,所以我想要最后定位的坐标?在此先感谢我非常接近我的目标,请提供帮助。

图片优先:

第二张图片:

【问题讨论】:

    标签: javascript jquery html html5-canvas


    【解决方案1】:

    如何获取可拖动/调整大小的图片信息(X/Y/Width/Height)

    当您拖动/调整图像大小时,此代码将报告您的图像信息:

          darthVaderGroup.on("dragend",function(){$("#info").text(getImageInfo());});
    
          function getImageInfo(){
              var image=darthVaderImg;
              return(
                  "   X/Y:"+
                  image.getAbsolutePosition().x+"/"+
                  image.getAbsolutePosition().y+" -- Width/Height:"+
                  image.getWidth()+"/"+
                  image.getHeight()          
              );
          }
    

    这是代码和小提琴:http://jsfiddle.net/m1erickson/Hm9uN/

    <!doctype html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.4.1.min.js"></script>
    
    <style>
        body{ background-color: ivory; padding:15px; }
        canvas{border:1px solid red;}
        #wrapper{ position:relative; width:400px; height:400px; }
        #Tshirt,#container_canvas{ position:absolute; top:0; left:0; }
    </style>
    
    <script>
    $(function(){
    
        function update(activeAnchor) {
          var group = activeAnchor.getParent();
          var topLeft = group.get('.topLeft')[0];
          var topRight = group.get('.topRight')[0];
          var bottomRight = group.get('.bottomRight')[0];
          var bottomLeft = group.get('.bottomLeft')[0];
          var image = group.get('.image')[0];
    
          var anchorX = activeAnchor.getX();
          var anchorY = activeAnchor.getY();
    
          // update anchor positions
          switch (activeAnchor.getName()) {
            case 'topLeft':
              topRight.setY(anchorY);
              bottomLeft.setX(anchorX);
              break;
            case 'topRight':
              topLeft.setY(anchorY);
              bottomRight.setX(anchorX);
              break;
            case 'bottomRight':
              bottomLeft.setY(anchorY);
              topRight.setX(anchorX); 
              break;
            case 'bottomLeft':
              bottomRight.setY(anchorY);
              topLeft.setX(anchorX); 
              break;
          }
    
          image.setPosition(topLeft.getPosition());
    
          var width = topRight.getX() - topLeft.getX();
          var height = bottomLeft.getY() - topLeft.getY();
          if(width && height) {
            image.setSize(width, height);
          }
    
          imgX=image.getAbsolutePosition().x;
          imgY=image.getAbsolutePosition().y;
          imgWidth=image.getWidth();
          imgHeight=image.getHeight();
    
        }
    
        function addAnchor(group, x, y, name) {
          var stage = group.getStage();
          var layer = group.getLayer();
    
          var anchor = new Kinetic.Circle({
            x: x,
            y: y,
            stroke: '#666',
            fill: '#ddd',
            strokeWidth: 2,
            radius: 8,
            name: name,
            draggable: true,
            dragOnTop: false
          });
    
          anchor.on('dragmove', function() {
            update(this);
            layer.draw();
          });
          anchor.on('mousedown touchstart', function() {
            group.setDraggable(false);
            this.moveToTop();
          });
          anchor.on('dragend', function() {
            group.setDraggable(true);
            layer.draw();
          });
          // add hover styling
          anchor.on('mouseover', function() {
            var layer = this.getLayer();
            document.body.style.cursor = 'pointer';
            this.setStrokeWidth(4);
            layer.draw();
          });
          anchor.on('mouseout', function() {
            var layer = this.getLayer();
            document.body.style.cursor = 'default';
            this.setStrokeWidth(2);
            layer.draw();
          });
    
          group.add(anchor);
        }
    
        function initStage(images) {
          var stage = new Kinetic.Stage({
            container: 'container_canvas',
            width: 578,
            height: 400
          });
          var darthVaderGroup = new Kinetic.Group({
            x: 270,
            y: 100,
            draggable: true
          });
          var layer = new Kinetic.Layer();
          layer.add(darthVaderGroup);
          stage.add(layer);
    
    
          var darthVaderImg = new Kinetic.Image({
            x: 0,
            y: 0,
            image: images.darthVader,
            width: 200,
            height: 138,
            name: 'image'
          });
    
          darthVaderGroup.add(darthVaderImg);
          addAnchor(darthVaderGroup, 0, 0, 'topLeft');
          addAnchor(darthVaderGroup, 200, 0, 'topRight');
          addAnchor(darthVaderGroup, 200, 138, 'bottomRight');
          addAnchor(darthVaderGroup, 0, 138, 'bottomLeft');
    
          darthVaderGroup.on('dragstart', function() {
            this.moveToTop();
          });
          stage.draw();
    
          darthVaderGroup.on("dragend",function(){$("#info").text(getImageInfo());});
    
          function getImageInfo(){
              var image=darthVaderImg;
              return(
                  "   X/Y:"+
                  image.getAbsolutePosition().x+"/"+
                  image.getAbsolutePosition().y+" -- Width/Height:"+
                  image.getWidth()+"/"+
                  image.getHeight()          
              );
          }
    
        }
    
      function putDesign(designSrc){
          designSrc = designSrc.split("images/"); 
          var sources = {
              darthVader: 'http://dl.dropbox.com/u/139992952/stackoverflow/love.png'
          };
          loadImages(sources, initStage);
      }
    
      function loadImages(sources, callback) {
        var images = {};
        var loadedImages = 0;
        var numImages = 0;
        for(var src in sources) {
          numImages++;
        }
        for(var src in sources) {
          images[src] = new Image();
          images[src].onload = function() {
            if(++loadedImages >= numImages) {
              callback(images);
            }
          };
          images[src].src = sources[src];
        }
      }
    
      putDesign("yourAssets");
    
    
    }); // end $(function(){});
    </script>
    
    </head>
    
    <body>
        <p>Info:<span id="info"></span></p><br/>
        <div id="wrapper">
            <img id="Tshirt" src="http://dl.dropbox.com/u/139992952/stackoverflow/Tshirt.png" width=167px height=167px>
            <div id="container_canvas"></div>            
        </div><br/>
    </body>
    </html>
    

    【讨论】:

    • 在脚本代码底部的第三行之后(loadImages(sources, initStage);)我只是像var x = image.getX(); var y = image.getY(); alert(x); alert(y);这样提醒这些行,所以它不会提醒任何值。
    猜你喜欢
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 2020-06-12
    • 2014-07-24
    • 2013-10-06
    • 1970-01-01
    • 2020-12-23
    相关资源
    最近更新 更多