使用HTML5画布创建图形后,如何使用鼠标拖动它们

5
我在 HTML 画布上画了一些圆,我的代码看起来像这样:
HTML:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>WebTunings</title>
    <link href="index.css" rel="stylesheet">
    <script src="index.js"></script>
</head>

<body>
<canvas id="canvas" width="600" height="600"></canvas>

<div id="controls">
    <p><label>Fill: <input id="fillBox" type="checkbox" checked="checked"></label></p>

    <div class="lightBorder">
        <p><input type="radio" name="shape" value="circle" checked="checked">Circle</p>
    </div>

    <p><input id="clearCanvas" type="button" value="reset"></p>
</div>

</body>
</html>

JavaScript:
var canvas,
    context,
    dragging = false,
    dragStartLocation,
    snapshot;


function getCanvasCoordinates(event) {
    var x = event.clientX - canvas.getBoundingClientRect().left,
        y = event.clientY - canvas.getBoundingClientRect().top;

    return {x: x, y: y};
}

function takeSnapshot() {
    snapshot = context.getImageData(0, 0, canvas.width, canvas.height);
}

function restoreSnapshot() {
    context.putImageData(snapshot, 0, 0);
}

function drawCircle(position) {
    var radius = Math.sqrt(Math.pow((dragStartLocation.x - position.x), 2) + Math.pow((dragStartLocation.y - position.y), 2));
    context.beginPath();
    context.arc(dragStartLocation.x, dragStartLocation.y, radius, 0, 2 * Math.PI, false);
    context.fillStyle = getRndColor();
}


function draw(position) {

    var fillBox = document.getElementById("fillBox"),
        shape = document.querySelector('input[type="radio"][name="shape"]:checked').value;
    if (shape === "circle") {
        drawCircle(position);
    }

    if (fillBox.checked) {
        context.fill();
    } else {
        context.stroke();
    }
}

function dragStart(event) {
    dragging = true;
    dragStartLocation = getCanvasCoordinates(event);
    takeSnapshot();
}

function drag(event) {
    var position;
    if (dragging === true) {
        restoreSnapshot();
        position = getCanvasCoordinates(event);
        draw(position, "polygon");
    }
}

function dragStop(event) {
    dragging = false;
    restoreSnapshot();
    var position = getCanvasCoordinates(event);
    draw(position, "polygon");
}

function getRndColor() {
    var r = 255*Math.random()|0,
        g = 255*Math.random()|0,
        b = 255*Math.random()|0;
    return 'rgb(' + r + ',' + g + ',' + b + ')';
}

function eraseCanvas(){
    context.clearRect(0, 0, canvas.width, canvas.height);
}


function init() {
    canvas = document.getElementById("canvas");
    context = canvas.getContext('2d');
    context.strokeStyle = 'green';
    context.lineWidth = 4;
    context.lineCap = 'round';
    clearCanvas = document.getElementById("clearCanvas");

    canvas.addEventListener('mousedown', dragStart, false);
    canvas.addEventListener('mousemove', drag, false);
    canvas.addEventListener('mouseup', dragStop, false);
    clearCanvas.addEventListener("click", eraseCanvas, false);

}

window.addEventListener('load', init, false);

现在我想做的是,每当我画多个圆圈时,我想选择一个随机的圆圈并将其拖到画布上的另一个位置,适用于每个圆圈。我只想使用 html5javascript,没有其他第三方库。有什么办法可以做到吗?任何帮助都将不胜感激......

你能给一个 JSFiddle 链接吗? - AL-zami
这是jsfiddle链接:http://jsfiddle.net/pro797/2a1xnh8e/ - Proloy
1个回答

23
< p > Canvas无法“记住”它绘制圆形或矩形的位置,因此您必须进行记忆。通常通过在JavaScript对象中定义每个圆形或矩形,并将所有这些图形保存在shapes []数组中来完成。

// an array of objects that define different shapes
var shapes=[];
// define 2 rectangles
shapes.push({x:10,y:100,width:30,height:30,fill:"#444444",isDragging:false});
shapes.push({x:80,y:100,width:30,height:30,fill:"#ff550d",isDragging:false});
// define 2 circles
shapes.push({x:150,y:100,r:10,fill:"#800080",isDragging:false});
shapes.push({x:200,y:100,r:10,fill:"#0c64e8",isDragging:false});

接下来,您可以在JavaScript中侦听鼠标事件。当浏览器发出鼠标事件时,您可以调用一个函数来响应该事件。以下是告诉浏览器您想要侦听鼠标事件的方法:

// listen for mouse events
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
canvas.onmousemove = myMove;
你可以使用鼠标事件函数(myDown、myUp、myMove)来完成拖动操作。
在mousedown事件(由myDown函数处理)中,您需要测试每个形状,以查看鼠标是否在数组中的某个形状内。如果鼠标在1个或多个形状内,则在这些形状上设置一个isDragging标志,并设置一个dragok标志,以指示您需要跟踪鼠标进行拖动操作。
在mousemove事件(由myMove函数处理)中,您需要将任何正在拖动的形状移动鼠标移动的距离。
在mouseup事件(由myUp函数处理)中,通过清除dragok标志来停止拖动操作。
以下是带注释的示例代码和演示:
// get canvas related references
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var BB=canvas.getBoundingClientRect();
var offsetX=BB.left;
var offsetY=BB.top;
var WIDTH = canvas.width;
var HEIGHT = canvas.height;

// drag related variables
var dragok = false;
var startX;
var startY;

// an array of objects that define different shapes
var shapes=[];
// define 2 rectangles
shapes.push({x:10,y:100,width:30,height:30,fill:"#444444",isDragging:false});
shapes.push({x:80,y:100,width:30,height:30,fill:"#ff550d",isDragging:false});
// define 2 circles
shapes.push({x:150,y:100,r:10,fill:"#800080",isDragging:false});
shapes.push({x:200,y:100,r:10,fill:"#0c64e8",isDragging:false});

// listen for mouse events
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
canvas.onmousemove = myMove;

// call to draw the scene
draw();

// draw a single rect
function rect(r) {
  ctx.fillStyle=r.fill;
  ctx.fillRect(r.x,r.y,r.width,r.height);
}

// draw a single rect
function circle(c) {
  ctx.fillStyle=c.fill;
  ctx.beginPath();
  ctx.arc(c.x,c.y,c.r,0,Math.PI*2);
  ctx.closePath();
  ctx.fill();
}

// clear the canvas
function clear() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

// redraw the scene
function draw() {
  clear();
  // redraw each shape in the shapes[] array
  for(var i=0;i<shapes.length;i++){
    // decide if the shape is a rect or circle
    // (it's a rect if it has a width property)
    if(shapes[i].width){
      rect(shapes[i]);
    }else{
      circle(shapes[i]);
    };
  }
}


// handle mousedown events
function myDown(e){

  // tell the browser we're handling this mouse event
  e.preventDefault();
  e.stopPropagation();

  // get the current mouse position
  var mx=parseInt(e.clientX-offsetX);
  var my=parseInt(e.clientY-offsetY);

  // test each shape to see if mouse is inside
  dragok=false;
  for(var i=0;i<shapes.length;i++){
    var s=shapes[i];
    // decide if the shape is a rect or circle               
    if(s.width){
      // test if the mouse is inside this rect
      if(mx>s.x && mx<s.x+s.width && my>s.y && my<s.y+s.height){
        // if yes, set that rects isDragging=true
        dragok=true;
        s.isDragging=true;
      }
    }else{
      var dx=s.x-mx;
      var dy=s.y-my;
      // test if the mouse is inside this circle
      if(dx*dx+dy*dy<s.r*s.r){
        dragok=true;
        s.isDragging=true;
      }
    }
  }
  // save the current mouse position
  startX=mx;
  startY=my;
}


// handle mouseup events
function myUp(e){
  // tell the browser we're handling this mouse event
  e.preventDefault();
  e.stopPropagation();

  // clear all the dragging flags
  dragok = false;
  for(var i=0;i<shapes.length;i++){
    shapes[i].isDragging=false;
  }
}


// handle mouse moves
function myMove(e){
  // if we're dragging anything...
  if (dragok){

    // tell the browser we're handling this mouse event
    e.preventDefault();
    e.stopPropagation();

    // get the current mouse position
    var mx=parseInt(e.clientX-offsetX);
    var my=parseInt(e.clientY-offsetY);

    // calculate the distance the mouse has moved
    // since the last mousemove
    var dx=mx-startX;
    var dy=my-startY;

    // move each rect that isDragging 
    // by the distance the mouse has moved
    // since the last mousemove
    for(var i=0;i<shapes.length;i++){
      var s=shapes[i];
      if(s.isDragging){
        s.x+=dx;
        s.y+=dy;
      }
    }

    // redraw the scene with the new rect positions
    draw();

    // reset the starting mouse position for the next mousemove
    startX=mx;
    startY=my;

  }
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<h4>Drag one or more of the shapes</h4>
<canvas id="canvas" width=300 height=300></canvas>


1
这是一个很酷的演示...我该如何管理z-index? 如果一个形状重叠了另一个形状,那么两个形状都将使用当前示例移动。 - Avi E. Koenig
1
为了记录,我正在创建一个点击和拖动的交互式演示,需要管理Z-索引。我的做法是给每个“形状”添加“zIndex”属性。然后在“draw”函数中,我的循环头是 for (shape of shapes.sort((a, b) => a.zIndex - b.zIndex))。希望这有所帮助! - JohnnyHammersticks
我应该提到,在“click”事件(上面答案中的myDown)期间,我正在重新排列shapes中的所有Z索引。一个简单而高效的方法是从您的集合中获取最大的Z索引,加1,并将您点击的对象的Z索引设置为该值。理论上,当您的索引达到INTMAX时,这将遇到问题,但除非您重新实现Cookie Clicker,否则没有人会保持打开该选项卡那么长时间;) - JohnnyHammersticks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接