javascript - JavaScript 画布和鼠标位置
问题描述
我正在尝试使用 JavaScript 在 HTML5 中制作绘图板,但工具(如铅笔、画笔等)的位置与我想象的不同。
我发现它是不同的,因为位图(?)所以我试图从人们已经问过的其他答案中修复它,但我失败了..
如何找到鼠标的正确位置?
这是我的 HTML 代码(我使用引导程序)
<div class="col-sm-10">
<canvas id="c" width="900" height="500"></canvas>
</div>
这是js(铅笔码不是我的,网上找的)
var el = document.getElementById('c'); //캔버스
var ctx = el.getContext('2d'); //붓
function pencil () {
var pos = getMousePos(el, e);
el.onmousedown = function() {
isDrawing = true;
ctx.moveTo(pos.X, pos.Y);
};
el.onmousemove = function() {
if (isDrawing) {
ctx.lineTo(pos.X, pos.Y);
ctx.stroke();
}
};
el.onmouseup = function() {
isDrawing = false;
};
}
解决方案
我在这里找到了 getMousePos 函数,它看起来像你正在做的事情。但是,它接受一个e
不会在您使用它的地方定义的参数(一个事件)。尝试将调用移动到getMousePos
定义事件的事件处理程序内部。
另外,isDrawing
没有定义。
var el = document.getElementById('c');
var ctx = el.getContext('2d'); //붓
ctx.strokeStyle = "#FF0000";
function pencil () {
var isDrawing = false;
el.onmousedown = function(e) {
var pos = getMousePos(el, e);
isDrawing = true;
ctx.moveTo(pos.x, pos.y);
};
el.onmousemove = function(e) {
var pos = getMousePos(el, e);
if (isDrawing) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
}
};
el.onmouseup = function() {
isDrawing = false;
};
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
pencil()
<div class="col-sm-10">
<canvas id="c" width="900" height="500"></canvas>
</div>
推荐阅读
- css - SCSS:-ms-prefix 导致 CSS 文件出错
- android - 在 Android 项目中使用 StateFlow
- php - 如何在 FreeBSD 上设置 PHP 语言环境?
- amazon-s3 - 如何将 S3 中的 DynamoJSON 数据读取到 Athena
- validation - 如何防止经过身份验证的用户通过 POSTMAN 发送类似请求?
- node.js - 如何在中间件中获取域,然后在 axios 调用 [Nuxt] 之前将其传递给组件/存储
- css - 如何使用 AWS SES 电子邮件模板添加背景图像
- javascript - 如何使用 ajax 加载背景图片 url?
- python - 如何使用pywin32获取outlook默认文件夹以外的文件夹
- c# - 使用 .NET core 使用 Nunit 和 SpecFlow 生成结果报告测试