【发布时间】:2021-11-27 07:25:24
【问题描述】:
我有这个代码,现在通过点击图表线我可以移动点击的点。它可以向上、向下、向左、向右移动,这很好,但我应该能够移动前 20 点和下 20 点来做
您也可以在这里查看https://jsbin.com/qumihizoje/1/edit?html,js,output
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var mouse = {};
var draggable = false;
context.lineWidth = 2;
context.strokeStyle = "blue";
var coordinates = [];
for (let i = 0; i < 300; i++) {
coordinates.push({ x: i, y: getRandomInt(80, 85) });
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
canvas.addEventListener("mousedown", function(e) {
handleMouseDown(e);
});
function handleMouseDown(e) {
mouse = oMousePos(canvas, e);
for (index = 0; index < coordinates.length; index++) {
context.beginPath();
context.arc( coordinates[index].x, coordinates[index].y, 5, 0, 2 * Math.PI );
if (context.isPointInPath(mouse.x, mouse.y)) {
draggable = index + 1;
break;
}
}
}
function drawPolygon() {
context.clearRect(0, 0, cw, ch);
context.beginPath();
context.moveTo(coordinates[0].x, coordinates[0].y);
for (index = 1; index < coordinates.length; index++) {
context.lineTo(coordinates[index].x, coordinates[index].y);
}
context.stroke();
}
canvas.addEventListener("mousemove", function(e) {
if (draggable) {
mouse = oMousePos(canvas, e);
coordinates[draggable - 1].x = mouse.x;
coordinates[draggable - 1].y = mouse.y;
drawPolygon();
}
});
canvas.addEventListener("mouseup", function(e) {
if (draggable) {
draggable = false;
}
});
function oMousePos(canvas, evt) {
var ClientRect = canvas.getBoundingClientRect();
return {
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
};
}
drawPolygon();
<canvas id="canvas"></canvas>
我只移动了一个点,如何解决?我需要使用纯js。
【问题讨论】:
-
您的第二个屏幕截图与第一个相同。
-
抱歉,我修好了截图
标签: javascript canvas charts html5-canvas