點評:繪制一個像素寬的細線,在使用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();
新聞熱點
疑難解答