不和不可以接物,不严不可以驭下。——林逋
分享几种canvas
消除锯齿的方式
1. 线条坐标增加0.5
1 2 3 4 5 6 7 8 9
| <canvas id="canvas1" width="200" height="200"></canvas> <script> var canvas = document.getElementById('canvas1'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(0, 0.5); ctx.lineTo(200, 0.5); ctx.stroke(); </script>
|
2. 使用高清画布
1 2 3 4 5 6 7 8 9 10 11
| <canvas id="canvas2" style="width:200px; height:200px;"></canvas> <script> var canvas = document.getElementById('canvas2'); var ctx = canvas.getContext('2d'); var dpr = window.devicePixelRatio || 1; var rect = canvas.getBoundingClientRect(); canvas.width = rect.width * dpr; canvas.height = rect.height * dpr; ctx.scale(dpr, dpr); </script>
|
3. 缩放画布进行图像修正
1 2 3 4 5 6 7 8 9 10 11
| <canvas id="canvas3" width="200" height="200"></canvas> <script> var canvas = document.getElementById('canvas3'); var ctx = canvas.getContext('2d'); var scale = window.devicePixelRatio; canvas.width *= scale; canvas.height *= scale; ctx.scale(scale, scale); </script>
|
4. 配置图像平滑属性
1 2 3 4 5 6 7
| <canvas id="canvas4" width="200" height="200"></canvas> <script> var canvas = document.getElementById('canvas4'); var ctx = canvas.getContext('2d'); ctx.imageSmoothingEnabled = true; </script>
|
5. 使用 hidpi-canvas
库
这个需要在您的项目中包含hidpi-canvas
库,示例假定您已经引入了该库。
1 2 3 4 5 6
| <canvas id="canvas5" width="200" height="200"></canvas> <script> var canvas = document.getElementById('canvas5'); </script>
|
6. Bicubic Interpolation的插值算法
这通常在图像处理库中实现,Canvas本身不直接支持,但可以通过引入外部库如fabric.js
或自定义函数实现。
7. ctx.translate(0.5, 0.5)
1 2 3 4 5 6 7
| <canvas id="canvas7" width="200" height="200"></canvas> <script> var canvas = document.getElementById('canvas7'); var ctx = canvas.getContext('2d'); ctx.translate(0.5, 0.5); </script>
|