【发布时间】:2020-08-09 08:35:25
【问题描述】:
我可以使用鼠标在 html 画布上的正确位置画一条线。下面是代码。
HTML:
<html>
<head></head>
<body onload="InitThis();">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="index.js"></script>
<div align="center">
<canvas id=c width="500" height="200" style="border:2px solid black"></canvas>
</div>
</body>
</html>
index.js:
var mousePressed = false;
var lastX, lastY;
var ctx;
function InitThis() {
ctx = document.getElementById('c').getContext("2d");
const canvas = document.querySelector('#c');
$('#c').mousedown(function (e) {
mousePressed = true;
Draw(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop, false);
});
$('#c').mousemove(function (e) {
if (mousePressed) {
Draw(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop, true);
}
});
$('#c').mouseup(function (e) {
mousePressed = false;
});
$('#c').mouseleave(function (e) {
mousePressed = false;
});
}
function Draw(x, y, isDown) {
if (isDown) {
ctx.beginPath();
ctx.strokeStyle = "blue";
ctx.lineWidth = 9;
ctx.lineJoin = "round";
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.closePath();
ctx.stroke();
}
lastX = x; lastY = y;
}
但是当我在 html 中包含视频并移动画布位置时,当我使用鼠标时正在绘制线条,但不是在我单击鼠标的正确位置。它被绘制在鼠标位置的下方。
HTML:
<html>
<head></head>
<body onload="InitThis();">
<link rel="stylesheet" href="index.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="index.js"></script>
<div align="center">
<video id=v controls loop autoplay muted>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type=video/mp4>-
</video>
<canvas id=c style="border:2px solid black"></canvas>
</div>
</body>
</html>
index.css:
#c {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 400;
height: 300;
}
#v {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 400;
height: 300;
}
index.js 与第一个程序相同。最初我认为这是由于视频元素而发生的。但即使在删除视频元素之后,同样的问题也会发生。我在想是因为“绝对”的立场。但是我需要在 index.css 中提到的相同位置的画布和视频元素。谁能告诉我如何解决这个问题。
注意:当我使用 codepen (https://codepen.io/adinakr/pen/OJymJNj) 进行测试时,这可以正常工作。但是当我直接在浏览器上尝试时,问题正在发生。
【问题讨论】:
标签: javascript html jquery css html5-canvas