Starburst shape drawn with canvas appearing very pixelated (aliased)
I'm trying to create a "starburst" effect using the canvas, but the segment lines appear incredibly pixelated. Am I doing something wrong?
var rays = 40;
var canvas = $("header canvas")[0];
var ctx = canvas.getContext("2d");
var centre = [canvas.width*0.2,canvas.height*0.90];
var radius = Math.sqrt(Math.pow(canvas.width,2)+Math.pow(canvas.height,2));
var colours = ["red","white"];
va开发者_运维技巧r segment = 2*Math.PI/rays;
for(var i=0;i<rays;i++){
ctx.beginPath();
ctx.moveTo(centre[0], centre[1]);
ctx.arc(
centre[0],
centre[1],
radius,
segment * i,
segment * (i+1),
false
);
ctx.lineTo(centre[0], centre[1]);
ctx.closePath();
ctx.fillStyle = colours[i % colours.length];
ctx.fill();
}
I'd suggest using vector graphics (ie SVG) instead of canvas. It will eliminate your problems of pixellated lines.
More specifically, if you use the Raphael Javascript library, your code could be virtually the same.
The added bonus is that Raphael also works in older versions of IE, as it can detect and switch to using VML if SVG isn't available.
Anti-aliasing is done by the browser. Right now your code will look excellent in Firefox 4 and IE9 but poor in webkit browsers.
There are plusses to the way chrome/safari do it, like this, which will look good on chrome but poor on Firefox 4.
People have asked the spec writer for a boolean controlling anti-aliasing, and he was opposed to the idea.
精彩评论