簡體   English   中英

如何通過在 html5/canvas 中拖動背景來移動對象?

[英]How do you move objects by dragging on the background in html5/canvas?

我希望能夠通過拖動它來創建一個可移動的畫布,但能夠將對象放置在畫布上,這些對象將相對於放置的位置保持原位。 我該怎么做?

例如,我在畫布上的不同位置放置了 4 張圖像。 然后我在畫布上的空白處拖動,所有對象都根據鼠標的移動而移動。 創建畫布具有無限空間的錯覺(因為我希望能夠在屏幕顯示的內容之外放置多個對象)。

我是否必須跟蹤對象本身,並在拖動空白區域時讓所有對象移動? 如果我在畫布上說了幾百個所述對象(不在視野中,但能夠使用這種拖動方法重新回到視野中),這將如何影響內存?

主要思想是我相對於鼠標移動翻譯畫布上下文。 請閱讀代碼中的注釋。

在這個例子中,我畫了一些圓圈。 你可以畫任何東西。

 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 = {} ox = (1 - Math.random() )* 3 * cw; oy = Math.random() * ch; or = (Math.random() * 20) + 10; o.color = color; o.draw = function(){ ctx.fillStyle = o.color; ctx.beginPath(); ctx.arc(ox,oy,or,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); dx = last_m.x - mx; dy = last_m.y - my; // the total dragged distance on mouse up Dx += dx; Dy += dy; }) canvas.addEventListener("mousemove",(evt)=>{ if(dragging){ last_m = oMousePos(canvas, evt); dx = last_m.x - mx + Dx; dy = last_m.y - my + Dy; // clear the context ctx.clearRect(-cw,0, 2*cw,ch); ctx.save(); //translate the context ctx.translate(dx, dy); //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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM