html5 边框锯齿,HTML5画布和抗锯齿

It's now 2018, and we finally have cheap ways to do something around it...

Indeed, since the 2d context API now has a filter property, and that this filter property can accept SVGFilters, we can build an SVGFilter that will keep only fully opaque pixels from our drawings, and thus eliminate the default anti-aliasing.

So it won't deactivate antialiasing per se, but provides a cheap way both in term of implementation and of performances to remove all semi-transparent pixels while drawing.

I am not really a specialist of SVGFilters, so there might be a better way of doing it, but for the example, I'll use a node to grab only fully opaque pixels.

var ctx = canvas.getContext('2d');

ctx.fillStyle = '#ABEDBE';

ctx.fillRect(0,0,canvas.width,canvas.height);

ctx.fillStyle = 'black';

ctx.font = '14px sans-serif';

ctx.textAlign = 'center';

// first without filter

ctx.fillText('no filter', 60, 20);

drawArc();

drawTriangle();

// then with filter

ctx.setTransform(1, 0, 0, 1, 120, 0);

ctx.filter = 'url(#remove-alpha)';

// and do the same ops

ctx.fillText('no alpha', 60, 20);

drawArc();

drawTriangle();

// to remove the filter

ctx.filter = 'none';

function drawArc() {

ctx.beginPath();

ctx.arc(60, 80, 50, 0, Math.PI * 2);

ctx.stroke();

}

function drawTriangle() {

ctx.beginPath();

ctx.moveTo(60, 150);

ctx.lineTo(110, 230);

ctx.lineTo(10, 230);

ctx.closePath();

ctx.stroke();

}

// unrelated

// simply to show a zoomed-in version

var zCtx = zoomed.getContext('2d');

zCtx.imageSmoothingEnabled = false;

canvas.onmousemove = function drawToZoommed(e) {

var x = e.pageX - this.offsetLeft,

y = e.pageY - this.offsetTop,

w = this.width,

h = this.height;

zCtx.clearRect(0,0,w,h);

zCtx.drawImage(this, x-w/6,y-h/6,w, h, 0,0,w*3, h*3);

}

And for the ones that don't like to append an element in their DOM, you can also save it as an external svg file and set the filter property to path/to/svg_file.svg#remove-alpha.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值