簡體   English   中英

使用html5畫布創建形狀后使用鼠標拖動形狀

[英]Dragging Shapes using mouse after creating them with html5 canvas

我在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沒有其他第三方庫。 有沒有辦法做到這一點? 任何幫助都會很棒......

畫布不會“記住”它繪制圓圈或矩形的位置,因此您必須進行記憶。 這通常通過在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+形狀內,則在這些1+形狀上設置isDragging標志,並設置dragok標志以指示您需要跟蹤鼠標以進行拖動。

  • 在鼠標移動事件(由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(rx,ry,r.width,r.height); } // draw a single rect function circle(c) { ctx.fillStyle=c.fill; ctx.beginPath(); ctx.arc(cx,cy,cr,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>sx && mx<s.x+s.width && my>sy && my<s.y+s.height){ // if yes, set that rects isDragging=true dragok=true; s.isDragging=true; } }else{ var dx=sx-mx; var dy=sy-my; // test if the mouse is inside this circle if(dx*dx+dy*dy<sr*sr){ 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> 

暫無
暫無

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

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