正统的HTML5 Canvas中以下编码
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(10, 100);
ctx.lineTo(300,100);
ctx.stroke();
运作結果绘图出来的其实不是1个像素宽度的线
觉得如何好粗啊,跟经常见到的网页页面版各种各样绘图线实际效果
很不1样,难道说HTML5 Canvas就想不到搞好点嘛
实际上这个压根缘故在于Canvas的绘图并不是从正中间刚开始的
而是从0~1,并不是从0.5~1 + 0~0.5的绘图方法,因此
致使fade在边沿,看上去线很宽。
处理方式有两个,1个是移位遮盖法,此外1种是管理中心
平移(0.5,0.5)。完成编码以下:
移位遮盖法我早已包装成1个初始context的涵数
/**
* <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();
要非常留意保证你的全部座标点是整数金额,不然HTML5会全自动完成边沿反锯齿
又致使你的1个像素平行线看上去变粗了。
运作实际效果:
如今实际效果如何,这个便是HTML5 Canvas画线的1个小窍门
感觉非常好请顶1下。