这是考虑到 nycnik 建议的答案的简化代码。代码效果更好,但比例和偏移量仍然关闭。单击拖动并释放,绘制的线看起来大约是 2 倍。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="st.css" media="all"/>
<script>
var x, y;
function getXY(canvas, e) {
var rect = canvas.getBoundingClientRect();
return [e.clientX - rect.left, e.clientY - rect.top];
}
function move(ca, e) {
}
function mark(ca, e) {
[x,y] = getXY(ca, e);
}
function clickDrag(ca, e) {
var c = ca.getContext("2d");
var x2, y2;
[x2,y2] = getXY(ca, e);
c.fillStyle='#00FF80';
c.lineStyle='#FFFF80';
c.moveTo(x,y);
c.lineTo(x2,y2);
c.stroke();
}
</script>
</head>
<body>
<div class="bg">
<canvas id="q13g" onmousedown="mark(this,event)" onmouseup="clickDrag(this, event)">
</canvas>
</div>
</body>
</html>