如何根据用户输入的 X、Y 点绘制 HTML5 Canvas 线?
我正在尝试在 Canvas 中构建平面图模型。目前,我的画布中有一个网格图像,并且用户可以通过单击并拖动鼠标来绘制线条。但是,这并不能保证直线。
无论如何,我是否可以在 html 页面中提供输入字段,供用户输入线条的开始和结束 x 和 y 坐标,并在我的画布代码中更新它?我是 JS/AJAX 的初学者,所以任何补救帮助都是值得赞赏的:)
现在,这是指示如何绘制线条的部分:
$(document).ready(function() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext("2d");
if(canvas.getContext) {
$('#canvas').mousedown(function (evt) {
var offset = $('#canvas').offset();
context.beginPath();
context.moveTo(20, 20);
});
$(document).mousemove(function(evt) {
var offset = $('#canvas').offset();
context.lineTo(evt.pageX - offset.left, evt.pageY - offset.top);
context.stroke();
}).mouseup(function() {
$(document).unbind('mousemove');
$(document).unbind('mouseup');
});
$('#clearcanvas').click(function () {
context.clearRect(0, 0, 600, 580);
});
}
});
我怀疑它涉及修改以下代码:
context.lineTo(evt.pageX - offset.left, evt.pageY - offset.top);
I am trying to build a floorplan model in Canvas. Currently I have a grid image in my canvas and have the ability for users to draw lines by clicking and dragging their mouse. But, this doesn't guarantee straight lines.
Is there anyway I can provide input fields in the html page for users to input the beginning and ending x and y coordinates of the lines, and have it updated in my canvas code? I'm a beginner when it comes to JS/AJAX, so any remedial help is appreciated :)
Right now, this is the section that dictates how the lines get drawn:
$(document).ready(function() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext("2d");
if(canvas.getContext) {
$('#canvas').mousedown(function (evt) {
var offset = $('#canvas').offset();
context.beginPath();
context.moveTo(20, 20);
});
$(document).mousemove(function(evt) {
var offset = $('#canvas').offset();
context.lineTo(evt.pageX - offset.left, evt.pageY - offset.top);
context.stroke();
}).mouseup(function() {
$(document).unbind('mousemove');
$(document).unbind('mouseup');
});
$('#clearcanvas').click(function () {
context.clearRect(0, 0, 600, 580);
});
}
});
I suspect it involves modifying following code:
context.lineTo(evt.pageX - offset.left, evt.pageY - offset.top);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
非常简单,您可以使用 4 个输入字段,并在按下按钮时获取每个输入字段的值
http://jsfiddle.net/TeGGx /
Very simply you could use 4 input fields and take the value of each when a button is pressed
http://jsfiddle.net/TeGGx/