如何通过在html5 / canvas中拖动背景来移动对象?

时间:2019-04-11 13:43:39

标签: javascript html5 canvas

我希望能够通过拖动它来创建可移动的画布,但是能够将对象放置在画布上,该对象相对于放置它们的位置将保持不变。我将如何去做?

例如,我将4张图像放置在画布上的不同位置。然后,我在画布上的空白区域上拖动,所有对象都根据鼠标的移动而移动。产生一种幻觉,认为画布具有无限的空间(因为我希望能够在屏幕显示的内容之外放置多个对象)。

我是否必须跟踪对象本身,并在拖动空白区域时使所有对象移动?如果我在画布上说了几百个这样的对象(不在视线范围内但可以使用此拖动方法重新显示),这将如何影响内存?

1 个答案:

答案 0 :(得分:0)

主要思想是,我相对于鼠标移动来转换画布上下文。请阅读代码中的注释。

在此示例中,我绘制了一些圆圈。您可以画其他任何东西。

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = window.innerWidth,
  cx = cw / 2;
let ch = canvas.height = window.innerHeight,
  cy = ch / 2;

//the mouse
let m = {x:0,y:0};//mouse coords on mouse down
let last_m = {x:0,y:0}//mouse coords on dragging
//distance
let d = {x:0,y:0};// distance while dragging
let D = {x:0,y:0};// distance on mouse up




// draw some circles
let circles = [];
let dragging = false;

function drawCircle(color){
  let o = {}
  o.x = (1 - Math.random() )* 3 * cw;
  o.y = Math.random() * ch;
  o.r = (Math.random() * 20) + 10;
  o.color = color;
  o.draw = function(){
    ctx.fillStyle = o.color;
    ctx.beginPath();
    ctx.arc(o.x,o.y,o.r,0,2*Math.PI);
    ctx.fill();
  }
  circles.push(o)
}


for(let i = 0; i < 70; i++){
drawCircle(`hsl(${i * 12},80%,60%)`)
}

for(let i = 0; i < circles.length; i++){circles[i].draw()}


//events
canvas.addEventListener("mousedown",(evt)=>{
  dragging = true;
  //the mouse position
  m = oMousePos(canvas, evt);
})

canvas.addEventListener("mouseup",(evt)=>{
  dragging = false;
  last_m = oMousePos(canvas, evt);
  d.x = last_m.x - m.x;
  d.y = last_m.y - m.y;
  // the total dragged distance on mouse up
  D.x += d.x;
  D.y += d.y;
})


canvas.addEventListener("mousemove",(evt)=>{
  
  if(dragging){
    
    last_m = oMousePos(canvas, evt);
    
    d.x = last_m.x - m.x + D.x;
    d.y = last_m.y - m.y + D.y;
    
    // clear the context
    ctx.clearRect(-cw,0, 2*cw,ch);
    
    ctx.save();
    
    //translate the context
    ctx.translate(d.x, d.y);
    //repaint everithing
    for(let i = 0; i < circles.length; i++){circles[i].draw()}
    
    ctx.restore()
  }
                              
})


// a function to detect the mouse position on the canvas
function oMousePos(canvas, evt) {
  var ClientRect = canvas.getBoundingClientRect();
  return { //objeto
    x: Math.round(evt.clientX - ClientRect.left),
    y: Math.round(evt.clientY - ClientRect.top)
  }
}
*{margin:0;padding:0;}
body {
  overflow: hidden;
}
canvas {
  background-color: #000;
}
<canvas id="canvas"></canvas>