简体   繁体   English

用鼠标移动画布形状

[英]Moving canvas shapes with mouse

After pressing a button, I'd like to draw a circle at the tip of the mouse pointer on a canvas and then place it when the user clicks again. 按下按钮后,我想在画布上鼠标指针的尖端绘制一个圆圈,然后在用户再次单击时将其放置。 Here's what I've got so far: 到目前为止,这是我得到的:

$("#button").click(function(e){
          var canvas = document.getElementById('MyCanvas');
          var context = canvas.getContext('2d');
          canvas.addEventListener('mousemove', function(evt) {
            var mousePos = getMousePos(canvas, evt);
            var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
            console.log(message);
            var nodehandle = document.getElementById('circle');
            if(mousePos.x && mousePos.y) {        
        nodehandle.x = mousePos.x;
        nodehandle.y = mousePos.y;
        flag = 1;
    }
          }, false);
    });

function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };
      }

My problem is that when I draw a circle like this: 我的问题是当我画一个圆形时:

function drawCircle(mouseX, mouseY){
  var c = document.getElementById("grid");
  var ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.arc(95,50,5,0,2*Math.PI);
  ctx.stroke();
}

I don't know how to select that circle (the getElementById('circle') returns null even if I add ctx.id='circle' to the drawCircle function). 我不知道如何选择该圆(即使我将ctx.id ='circle'添加到drawCircle函数中,getElementById('circle')也会返回null)。 I'm also going to need to erase and redraw the circle each time the mouse moves, and I'm sure there's a nice way to do that but I'm not aware of it. 每当鼠标移动时,我还需要擦除并重画圆圈,我敢肯定有一种不错的方法,但我不知道。

Anything you draw on the canvas--like circles, are just like dried paint on the canvas. 您在画布上绘制的所有内容(例如圆圈)都像画布上的干漆一样。

Your circles cannot be selected or moved like html elements. 您的圈子无法像html元素一样选择或移动。

To move a circle you must clear the canvas and redraw the circle at a different location. 要移动圆,必须清除画布,然后在其他位置重新绘制圆。

It's convenient to store info about the circle in an object. 将有关圆的信息存储在对象中很方便。

var circle1 = { centerX:100, centerY=100, radius=20 }

And you can draw circle1 using that info: 您可以使用该信息绘制circle1:

ctx.beginPath();
ctx.arc(circle1.centerX, circle1.centerY, circle1.radius, 0,Math.PI*2);
ctx.closePath();
ctx.fill();

For more than 1 circle you can create a circles array and put each circle object into that array 对于一个以上的圆形,您可以创建一个圆形数组并将每个圆形对象放入该数组中

var circles=[];
circles.push(circle1);

Then to "move" a circle, just change the object's centerX/centerY to the mouse position and redraw all the circles on the canvas. 然后要“移动”一个圆,只需将对象的centerX / centerY更改为鼠标位置,然后在画布上重新绘制所有圆。

circle1.centerX=mouseX;
circle1.centerY=mouseY;

// Clear the canvas and redraw all circles
// The "moved" circle will be redrawn at its new position

function drawAll(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    for(var i=0;i<circles.length;i++){
        var c=circles[i];
        ctx.beginPath();
        ctx.arc(c.centerX,c.centerY,c.radius,0,Math.PI*2);
        ctx.closePath();
        ctx.fillStyle=c.color;
        ctx.fill();
    }
}

You can use Html radio buttons to determine which action a mouse-click will do: 您可以使用HTML单选按钮来确定鼠标单击将执行的操作:

  • Create a new circle at the mouse position, or 在鼠标位置创建一个新圆,或者
  • Select the circle under the mouse position, or 选择鼠标位置下方的圆圈,或
  • "Move" the currently selected circle “移动”当前选定的圈子

Here's example code and a Demo: http://jsfiddle.net/m1erickson/CEB7T/ 这是示例代码和演示: http : //jsfiddle.net/m1erickson/CEB7T/

<!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>
<style>
    body{ background-color: ivory; }
    #canvas{border:1px solid red;}
</style>
<script>
$(function(){

    // get references to the canvas and its context
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var $canvas=$("#canvas");

    // get the canvas position on the page
    // used to get mouse position
    var canvasOffset=$canvas.offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var scrollX=$canvas.scrollLeft();
    var scrollY=$canvas.scrollTop();
    ctx.lineWidth=3;

    // save info about each circle in an object
    var circles=[];
    var selectedCircle=-1;

    // the html radio buttons indicating what action to do upon mousedown
    var $create=$("#rCreate")[0];
    var $select=$("#rSelect")[0];
    var $move=$("#rMove")[0];

    // draw all circles[]
    function drawAll(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        for(var i=0;i<circles.length;i++){
            var c=circles[i];
            ctx.beginPath();
            ctx.arc(c.cx,c.cy,c.radius,0,Math.PI*2);
            ctx.closePath();
            ctx.fillStyle=c.color;
            ctx.fill();
            // if this is the selected circle, highlight it
            if(selectedCircle==i){
                ctx.strokeStyle="red";
                ctx.stroke();
            }
        }
    }

    function handleMouseDown(e){
      e.preventDefault();
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);

      if($create.checked){
          // create a new circle a the mouse position and select it
          circles.push({cx:mouseX,cy:mouseY,radius:10,color:randomColor()});
          selectedCircle=circles.length-1;
      }
      if($select.checked){
          // unselect any selected circle
          selectedCircle=-1;
          // iterate circles[] and select a circle under the mouse
          for(var i=0;i<circles.length;i++){
              var c=circles[i];
              var dx=mouseX-c.cx;
              var dy=mouseY-c.cy;
              var rr=c.radius*c.radius;
              if(dx*dx+dy*dy<rr){ selectedCircle=i; }
          }
      }
      if($move.checked && selectedCircle>=0){
          // move the selected circle to the mouse position
          var c=circles[selectedCircle];
          c.cx=mouseX;
          c.cy=mouseY;
      }

      // redraw all circles
      drawAll();
    }

    // return a random color
    function randomColor(){ 
        return('#'+Math.floor(Math.random()*16777215).toString(16));
    }

    // handle mousedown events
    $("#canvas").mousedown(function(e){handleMouseDown(e);});

}); // end $(function(){});
</script>
</head>
<body>
    <input type="radio" name="grp1" id="rCreate" checked>Click will create a new circle.<br>
    <input type="radio" name="grp1" id="rSelect">Click will select an existing circle.<br>
    <input type="radio" name="grp1" id="rMove">Click will move selected circle.<br>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM