这是我第一次在Javascript中使用Canvas。我试图划线,差不多。这是我在某些部分中获得的内容(如下图所示)。有时候这条线看起来是正确的,但大部分时间都是这样的。正如你所看到的那样,它看起来有点突破,它看起来更暗。我试图找出原因,但没有运气。
这是我的代码。它还不是很干净,因为它还在开发中:
var canvas = document.getElementById("canvas");
var Point = function(x, y) {
this.startX = x;
this.startY = y;
};
var Interval = function(x, y) {
this.jumpX = x;
this.jumpY = y;
};
var points = [
[
new Point(340, 130), // point start
new Point(220, 130), // end first line
new Point(220, 70), // end second line
new Interval(-10, -10),
],
[
new Point(560, 80), // point start
new Point(660, 80), // end first line
new Point(660, 20), // end second line
new Interval(10, -10),
],
[
new Point(620, 230), // point start
new Point(770, 230), // end first line
new Point(770, 150), // end second line
new Interval(10, -10),
],
[
new Point(620, 230), // point start
new Point(770, 230), // end first line
new Point(770, 150), // end second line
new Interval(10, -10),
],
];
var ctx = canvas.getContext('2d');
ctx.strokeStyle = "#DFC270";
var func = function(points, text, j1, j2) {
var startX = points[0].startX,
startY = points[0].startY,
tempX = startX,
tempY = startY,
line1X = points[1].startX,
line1Y = points[1].startY,
line2X = points[2].startX,
line2Y = points[2].startY;
ctx.lineWidth = 1;
ctx.beginPath();
var inter = function() {
ctx.moveTo(startX, startY);
// console.log(tempY + j1);
if (tempY == line1Y && tempX == line1X) {
if (startX !== line2X) {
startX += j2;
}
if (startY !== line2Y) {
startY += j2;
}
if (startY == line2Y && startX == line2X) {
ctx.beginPath();
ctx.lineWidth = 1;
ctx.arc(startX, startY-j2, 5, 0, 2*Math.PI);
ctx.fillStyle = "#DFC270";
ctx.fill();
ctx.closePath();
ctx.stroke();
clearInterval(inter);
return;
}
} else {
if (startX !== line1X && tempX !== line1X) {
startX += j1;
tempX = startX;
}
if (startY !== line1Y && tempY !== line1Y) {
startY += j1;
tempY = startY;
}
}
window.requestAnimationFrame(inter);
ctx.lineTo(startX, startY);
ctx.stroke();
};
window.requestAnimationFrame(inter);
};
for (var i = 0; i < points.length; ++i) {
var interval = points[i][points[i].length-1];
func(points[i], 'test', interval.jumpX, interval.jumpY);
};
这里是一个小提琴,我也可以重新创建它
答案 0 :(得分:3)
这是因为调用了beginPath()
两次,删除了if语句下的额外方法调用:
var func = function(points, text, j1, j2) {
...
ctx.beginPath(); // <-- Already called here
...
var inter = function() {
if (startY == line2Y && startX == line2X) {
//ctx.beginPath(); <-- Remove this
ctx.lineWidth = 1;
...
答案 1 :(得分:0)
问题在于,在绘制圆的点时,您从未完成最终路径描边。
在第68行调用这样的笔画函数
if (startY == line2Y && startX == line2X ) {
ctx.stroke();
ctx.beginPath();
ctx.lineWidth = 1;
ctx.arc(startX, startY-j2, 5, 0, 2*Math.PI);
ctx.fillStyle = "#DFC270";
ctx.fill();
ctx.closePath();
ctx.stroke();
clearInterval(inter);
return;