簡體   English   中英

雙擊畫布上的刪除點

[英]Remove point on double click on canvas

我有一個畫布,用戶可以在其上單擊任意部分來繪制點。 眾所周知,我們必須給用戶撤消他完成的動作的可能性。 這是我遇到的問題,如何編程代碼以允許用戶雙擊要刪除的點來刪除該點?

<canvas id="canvas" width="160" height="160" style="cursor:crosshair;"></canvas>

1-代碼繪制畫布並在其中加載圖像

var canvasOjo1 = document.getElementById('canvas'),
context1 = canvasOjo1.getContext('2d');
ojo1();

function ojo1()
{

base_image1 = new Image();
base_image1.src = 'https://www.admedicall.com.do/admedicall_v1//assets/img/patients-pictures/620236447.jpg';
base_image1.onload = function(){
context1.drawImage(base_image1, 0, 0);
}
}

2-代碼畫點

$("#canvas").click(function(e){
getPosition(e); 
});

var pointSize = 3;

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

drawCoordinates(x,y);
}

function drawCoordinates(x,y){  
var ctx = document.getElementById("canvas").getContext("2d");


ctx.fillStyle = "#ff2626"; // Red color

ctx.beginPath();
ctx.arc(x, y, pointSize, 0, Math.PI * 2, true);
ctx.fill();
}

我的小提琴: http : //jsfiddle.net/xpvt214o/834918/

通過將鼠標懸停在圖像上,我們看到一個十字形以創建該點。

如果我要雙擊創建一個點,該如何刪除?

先感謝您。

請首先閱讀此答案,以區分單擊事件和雙擊事件,因為這很棘手。

為了清楚起見,我通過刪除不相關的內容簡化了您的代碼。

還請閱讀我的代碼的注釋。

 let pointSize = 3; var points = []; var timeout = 300; var clicks = 0; const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); let cw = (canvas.width = 160); let ch = (canvas.height = 160); function getPosition(event) { var rect = canvas.getBoundingClientRect(); return { x: event.clientX - rect.left, y: event.clientY - rect.top }; } function drawCoordinates(point, r) { ctx.fillStyle = "#ff2626"; // Red color ctx.beginPath(); ctx.arc(point.x, point.y, r, 0, Math.PI * 2, true); ctx.fill(); } canvas.addEventListener("click", function(e) { clicks++; var m = getPosition(e); // this point won't be added to the points array // it's here only to mark the point on click since otherwise it will appear with a delay equal to the timeout drawCoordinates(m, pointSize); if (clicks == 1) { setTimeout(function() { if (clicks == 1) { // on click add a new point to the points array points.push(m); } else { // on double click // 1. check if point in path for (let i = 0; i < points.length; i++) { ctx.beginPath(); ctx.arc(points[i].x, points[i].y, pointSize, 0, Math.PI * 2, true); if (ctx.isPointInPath(mx, my)) { points.splice(i, 1); // remove the point from the array break;// if a point is found and removed, break the loop. No need to check any further. } } //clear the canvas ctx.clearRect(0, 0, cw, ch); } points.map(p => { drawCoordinates(p, pointSize); }); clicks = 0; }, timeout); } }); 
 body { background: #20262E; padding: 20px; } 
 <canvas id="canvas" style="cursor:crosshair;border:1px solid white"></canvas> 

暫無
暫無

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

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