您可能会看到这是我的第一篇帖子,所以借口使用stackoverflow可以解决任何初学者的错误。
我目前正在制作一个平面图Web应用程序,您可以在其中绘制线条来创建房屋的平面图。
想要的效果是:当用户点击一次时,用户绘制一个临时线,其中起点X是点击的点,目标点Z是用户可以移动的鼠标。我目前正在使用画布来实现这种效果,但不知何故,这条线是看不见的或者不存在。我尝试了一些调试,这些调试把我带到了这里。
这是当前的代码:
function drawLineXY(fromXY, toXY) {
if(!lineElem) {
lineElem = document.createElement('canvas');
lineElem.style.position = "absolute";
lineElem.style.zIndex = 100;
document.body.appendChild(lineElem);
console.log("Added line element");
}
var leftpoint, rightpoint;
if(fromXY.x < toXY.x) {
leftpoint = fromXY;
rightpoint = toXY;
} else {
leftpoint = toXY;
rightpoint = fromXY;
}
var lineWidthPix = 4;
var gutterPix = 0;
var origin = {x:leftpoint.x-gutterPix,
y:Math.min(fromXY.y, toXY.y)-gutterPix};
lineElem.width = "1000px";
lineElem.height = "1000px";
lineElem.style.left = "0px";
lineElem.style.top = "0px";
var ctx = lineElem.getContext('2d');
// Use the identity matrix while clearing the canvas
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, lineElem.width, lineElem.height);
ctx.restore();
ctx.lineWidth = 4;
ctx.strokeStyle = '#09f';
ctx.beginPath();
ctx.moveTo(fromXY.x - origin.x, fromXY.y - origin.y);
ctx.lineTo(toXY.x - origin.x, toXY.y - origin.y);
ctx.stroke();
console.log("drawing line..");
}
function moveHandler(evt) {
var startCentre, startBounds;
var targets = [];
if(clicked.length === 2) {
targets = clicked;
} else if(clicked.length === 1) {
targets.push(clicked[0]);
if(typeof hoverElement !== 'undefined') {
targets.push(hoverElement);
}
}
if(targets.length == 2) {
var start = {x:targets[0], y:targets[0]};
var end = {x:targets[1], y:targets[1]};
drawLineXY(start, end);
} else if(targets.length == 1) {
var start = {x:targets[0], y:targets[0]};
drawLineXY(start, {x:evt.clientX, y:evt.clientY});
}
};
function clickHandler(e) {
if(clicked.length == 2) {
clicked = [];
}
clicked.push(e.target);
};
document.onclick = clickHandler;
document.onmousemove = moveHandler;
正如你在drawLineXY的最后一行中看到的那样,我已经制作了一个调试控制台日志“绘图线”这就像我移动鼠标一样。喜欢它应该。但没有线,有人有帮助吗?
PS:#canvas在style.css中指定。
我创建了一个非常基本的例子,可能是你想要实现的:
let c, ctx, fromXY, toXY;
window.onload = function(){
document.onclick = clickHandler;
document.onmousemove = moveHandler;
c = document.getElementById("myCanvas");
ctx = c.getContext("2d");
reset();
}
function draw(){
clear();
ctx.beginPath();
ctx.moveTo(fromXY.x, fromXY.y);
ctx.lineTo(toXY.x, toXY.y);
ctx.stroke();
ctx.closePath();
}
function clear(){
ctx.clearRect(0, 0, c.width, c.height);
}
function reset() {
fromXY = {};
toXY = {};
}
function moveHandler(e) {
if(typeof fromXY.x !== "undefined"){
toXY.x = e.clientX;
toXY.y = e.clientY;
draw();
}
}
function clickHandler(e) {
if(typeof fromXY.x === "undefined"){
fromXY.x = e.clientX;
fromXY.y = e.clientY;
}else{
reset();
}
}
<canvas id="myCanvas" height="500" width="500"></canvas>
你可以在draw()
函数中设置行选项,如果你想让行保持不变,你可以将它们的fromXY
和toXY
保存在一个数组中并重绘它们。