毛边效果 html,Html5 Canvas画线有毛边解决方法

Html5 Canvas 所有的画线指令画出来的线条都有毛边(比如 lineTo, arcTo,strokeRect),这是因为在Canvas中整数坐标值对应的位置恰巧是屏幕象素点中间的夹缝,那么当按这样的坐标进行线条渲染时所要用到的就是夹缝两边的象素点,这样即便设置了lineWidth为1也将看到两个象素效果的线条,解决方法原象素点+0.5进行偏移。

下面是处理前后的效果比较:

canvasTest

var MyCanvas = function(boxObj, width, height) {

//序号、计数

this.index = arguments.callee.prototype.Count = (arguments.callee.prototype.Count || 0) + 1;

var cvs = document.createElement("canvas");

cvs.id = "myCanvas" + this.index;

cvs.width = width || 800;

cvs.height = height || 600;

(boxObj || document.body).appendChild(cvs);

//excanvas框架中针对ie加载canvas延时问题手动初始化对象

if (typeof G_vmlCanvasManager != "undefined") G_vmlCanvasManager.initElement(cvs);

//2D画布对象

this.ctx = cvs.getContext("2d");

/* * 绘制线条

* @ops JSON对象,可按实际支持属性扩展,示例: { lineWidth:1,strokeStyle:'rgb(255,255,255)' }

* @dotXY:{ x:0, y:0 } ||[{ x:0, y:0 },{ x:0, y:0 }]

*/

this.drawLine = function(dotXY, ops) {

this.ctx.beginPath();

for (var att in ops) this.ctx[att] = ops[att];

dotXY = dotXY.constructor == Object ? [dotXY || { x: 0, y: 0}] : dotXY;

this.ctx.moveTo(dotXY[0].x, dotXY[0].y);

for (var i = 1, len = dotXY.length; i < len; i++) this.ctx.lineTo(dotXY[i].x, dotXY[i].y);

this.ctx.stroke();

};

};

window.οnlοad=function(){

var c1 = new MyCanvas();

c1.drawLine([{ x: 10, y: 10 }, { x: 10, y: 200 }],{lineWidth:2,strokeStyle:'rgb(0,0,0)'});

c1.drawLine([{ x: 11, y: 10 }, { x: 11, y: 200 }],{lineWidth:2,strokeStyle:'rgb(255,255,255)'});

c1.drawLine([{ x: 100, y: 10 }, { x: 100, y: 200 }],{lineWidth:1,strokeStyle:'rgb(0,0,0)'}); //普通线

c1.drawLine([{ x: 200.5, y: 10 }, { x: 200.5, y: 200 }],{lineWidth:1,strokeStyle:'rgb(0,0,0)'}); //+0.5偏移

}

↓ 处理的  ↓ 普通的  ↓ +0.5偏移的

4048144ac2975f5ffae359aae54f8d1a.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值