【发布时间】:2023-03-02 22:53:01
【问题描述】:
我在这样的 div 中有一个画布
<div class="col-md-6">
<img src="{{ image }}" class="img-class img-thumbnail img-responsive">
<canvas id="can" class="hidden" style="position: absolute; width: 100%; height: 100%; top: 0px; left: 0px;"></canvas>
<div class="hidden hover-div" style="position: absolute; width: 100%; height: 100%; background-color: rgba(128, 128, 128, 0.07); top: 0;">
</div>
</div>
以及用它画线的代码
var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
dot_flag = false;
var x = "black",
y = 2;
function initialize() {
canvas = document.getElementById('can');
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
canvas.addEventListener("mousemove", function (e) {
findxy('move', e)
}, false);
canvas.addEventListener("mousedown", function (e) {
findxy('down', e)
}, false);
canvas.addEventListener("mouseup", function (e) {
findxy('up', e)
}, false);
canvas.addEventListener("mouseout", function (e) {
findxy('out', e)
}, false);
}
function draw() {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}
function findxy(res, e) {
if (res == 'down') {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
flag = true;
dot_flag = true;
if (dot_flag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currX, currY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res == 'up' || res == "out") {
flag = false;
}
if (res == 'move') {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw();
}
}
}
它可以工作,但 x,y 坐标已关闭,需要帮助解决此问题。
这是一个屏幕记录演示它的行为https://youtu.be/e8SUUZF81rk
与鼠标相比,画布上的 y 位置远低于鼠标,而 x 则稍微靠右。
我从这里的一个示例中得到了这段代码,并对其进行了一些编辑。
【问题讨论】:
-
如果你把那个短的 youtube 视频转换成 .gif 并直接放在问题中会更好。
标签: javascript canvas