好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

HTML5Canvas中绘制一个像素宽的细线实现代码详情

正统的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(); 

要特别注意确保你的所有坐标点是整数,否则HTML5会自动实现边缘反锯齿

又导致你的一个像素直线看上去变粗了。

运行效果:


现在效果怎么样,这个就是HTML5 Canvas画线的一个小技巧

觉得不错请顶一下。

以上就是HTML5 Canvas中绘制一个像素宽的细线实现代码详情的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!

查看更多关于HTML5Canvas中绘制一个像素宽的细线实现代码详情的详细内容...

  阅读:63次