如何打开抗混叠在画布上.
下面的代码没有画出一条平滑的线:
var context = mainCanv.getContext("2d");
if (context) {
context.moveTo(0,0);
context.lineTo(100,75);
context.strokeStyle = "#df4b26";
context.lineWidth = 3;
context.stroke();
}发布于 2010-11-23 21:27:23
反混叠不能打开或关闭,并由浏览器控制.
发布于 2013-08-23 14:49:18
你可以把画布翻译成半像素的距离。
ctx.translate(0.5, 0.5);最初,画布在物理像素之间的定位点。
发布于 2018-03-19 07:22:12
现在是2018年,我们终于有了廉价的方法来做些什么.
事实上,由于2d上下文API现在有一个filter属性,并且这个过滤器属性可以接受SVGFilters,所以我们可以构建一个SVGFilter,它将只保留我们绘图中完全不透明的像素,从而消除默认的反混叠。
因此,它不会停用反走样本身,但提供了一种廉价的方式,无论是在实现和性能,以删除所有半透明像素,同时绘制。
我并不是SVGFilters的真正专家,所以可能有更好的方法来实现它,但是对于这个例子,我将使用一个节点来只获取完全不透明的像素。
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);
}<svg width="0" height="0" style="position:absolute;z-index:-1;">
<defs>
<filter id="remove-alpha" x="0" y="0" width="100%" height="100%">
<feComponentTransfer>
<feFuncA type="discrete" tableValues="0 1"></feFuncA>
</feComponentTransfer>
</filter>
</defs>
</svg>
<canvas id="canvas" width="250" height="250" ></canvas>
<canvas id="zoomed" width="250" height="250" ></canvas>
对于那些不喜欢在DOM中追加<svg>元素的人,也可以将其保存为外部svg文件,并将filter属性设置为path/to/svg_file.svg#remove-alpha。
https://stackoverflow.com/questions/4261090
复制相似问题