点评:绘制一个像素宽的细线,在使用HTML5 Canvas实现时要特别注意确保你的所有坐标点是整数,否则HTML5会自动实现边缘反锯齿,感兴趣的朋友可以看下效果图
正统的HTML5 Canvas中如下代码复制代码
代码如下:
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(10, 100);
ctx.lineTo(300,100);
ctx.stroke();
复制代码
代码如下:
/**
* <p> draw one pixel line </p>
* @param fromX
* @param formY
* @param toX
* @param toY
* @param backgroundColor - default is white
* @param vertical - boolean
*/
CanvasRenderingContext2D.prototype.onePixelLineTo = function(fromX, fromY, toX, toY, backgroundColor, vertical) {
var currentStrokeStyle = this.strokeStyle;
this.beginPath();
this.moveTo(fromX, fromY);
this.lineTo(toX, toY);
this.closePath();
this.lineWidth=2;
this.stroke();
this.beginPath();
if(vertical) {
this.moveTo(fromX+1, fromY);
this.lineTo(toX+1, toY);
} else {
this.moveTo(fromX, fromY+1);
this.lineTo(toX, toY+1);
}
this.closePath();
this.lineWidth=2;
this.strokeStyle=backgroundColor;
this.stroke();
this.strokeStyle = currentStrokeStyle;
};
复制代码
代码如下:
ctx.save();
ctx.translate(0.5,0.5);
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(10, 100);
ctx.lineTo(300,100);
ctx.stroke();
ctx.restore();
新闻热点
疑难解答