【发布时间】:2015-01-04 10:44:31
【问题描述】:
最近我开始玩 canvas 元素。现在我可以用鼠标在画布上画线(我想画多少线)。您可以在代码中看到它:https://jsfiddle.net/saipavan579/a6L3ka8p/。
var ctx = tempcanvas.getContext('2d'),
mainctx = canvas.getContext('2d'),
w = canvas.width,
h = canvas.height,
x1,
y1,
isDown = false;
tempcanvas.onmousedown = function(e) {
var pos = getPosition(e, canvas);
x1 = pos.x;
y1 = pos.y;
isDown = true;
}
tempcanvas.onmouseup = function() {
isDown = false;
mainctx.drawImage(tempcanvas, 0, 0);
ctx.clearRect(0, 0, w, h);
}
tempcanvas.onmousemove = function(e) {
if (!isDown) return;
var pos = getPosition(e, canvas);
x2 = pos.x;
y2 = pos.y;
ctx.clearRect(0, 0, w, h);
drawEllipse(x1, y1, x2, y2);
}
function drawEllipse(x1, y1, x2, y2) {
var radiusX = (x2 - x1) * 0.5,
radiusY = (y2 - y1) * 0.5,
centerX = x1 + radiusX,
centerY = y1 + radiusY,
step = 0.01,
a = step,
pi2 = Math.PI * 2 - step;
ctx.beginPath();
ctx.moveTo(x1,y1);
for(; a < pi2; a += step) {
ctx.lineTo(x2,y2);
}
ctx.closePath();
ctx.strokeStyle = '#000';
ctx.stroke();
}
function getPosition(e, gCanvasElement) {
var x;
var y;
x = e.pageX;
y = e.pageY;
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
return {x:x, y:y};
};
现在我想以与绘制线条相同的方式绘制箭头线(用于指向图像上的某个特定点)。怎么能这样做?提前谢谢你。
【问题讨论】:
-
只在行尾画一个三角形?
-
但我们不知道用户画线的方向
-
没有?在我的评论中,我说“在行尾”,这样你就知道方向了。
-
对不起。但是我怎么知道其他两点呢?
-
这是 Ted Hopp 的explained some maths of triangles。
标签: javascript html canvas