Reputation: 177
I have these functions to draw regular polygons or any shape defined by an array of points.
function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
if (sides < 3) return;
var a = (Math.PI * 2)/sides;
a = anticlockwise?-a:a;
ctx.save();
ctx.translate(x,y);
ctx.rotate(startAngle);
ctx.moveTo(radius, 0);
for (var i = 1; i < sides; i++) {
ctx.lineTo(radius*Math.cos(a*i), radius*Math.sin(a*i));
}
ctx.closePath();
ctx.restore();
}
function plotpolygon(radius, sides, color) {
var context = document.getElementById("logo-canvas").getContext('2d');
context.beginPath();
polygon(context, 256, 256, radius, sides, -Math.PI/2);
context.fillStyle = color;
context.fill();
context.stroke();
}
function plotshape(xpoints, ypoints, color) {
var context = document.getElementById("logo-canvas").getContext('2d');
context.beginPath;
context.moveTo(xpoints[0], ypoints[0]);
for (var i=1; i < xpoints.length; i++) {
context.lineTo(xpoints[i], ypoints[i]);
}
context.closePath();
context.fillStyle = color;
context.fill();
context.stroke();
}
The polygons and shapes are fine, the problem is the fill color. If I call in the following order:
plotpolygon(94, 3, 'yellow');
plotshape(xpoints, ypoints, 'brown');
The result should be yellow triangle with brown shape partially overlapping it. However, I get the place where shapes overlap - yellow, places where not overlapped - brown. I have tried composition as suggested by mozilla but it didn't help.
What's is more strange to me is that I have more polygons on the canvas, putting them always on top - most of them are overlapped, but they have their own colors fine. It is when I add a shape the problem starts to occur..
Upvotes: 0
Views: 1059
Reputation: 105035
You have a typo that causes the first triangle drawing styles to be continued in the plotshape.
Fix: the beginPath inside plotshape must have parentheses:
ctx.beginPath();
Slightly refactored Demo: http://jsfiddle.net/m1erickson/adHdr/
Upvotes: 1