当前位置:Gxlcms > html代码 > Html5中Canvas画线有毛边如何解决

Html5中Canvas画线有毛边如何解决

时间:2021-07-01 10:21:17 帮助过:31人阅读

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

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

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  5. <title>canvasTest</title>
  6. <script type="text/javascript" src="http://www.pyzy.net/Demo/html5_cancas_js/excanvas.js"></script>
  7. <script type="text/javascript">
  8. var MyCanvas = function(boxObj, width, height) {
  9. //序号、计数
  10. this.index = arguments.callee.prototype.Count = (arguments.callee.prototype.Count || 0) + 1;
  11. var cvs = document.createElement("canvas");
  12. cvs.id = "myCanvas" + this.index;
  13. cvs.width = width || 800;
  14. cvs.height = height || 600;
  15. (boxObj || document.body).appendChild(cvs);
  16. //excanvas框架中针对ie加载canvas延时问题手动初始化对象
  17. if (typeof G_vmlCanvasManager != "undefined") G_vmlCanvasManager.initElement(cvs);
  18. //2D画布对象
  19. this.ctx = cvs.getContext("2d");
  20. /* * 绘制线条
  21. * @ops JSON对象,可按实际支持属性扩展,示例: { lineWidth:1,strokeStyle:'rgb(255,255,255)' }
  22. * @dotXY:{ x:0, y:0 } ||[{ x:0, y:0 },{ x:0, y:0 }]
  23. */
  24. this.drawLine = function(dotXY, ops) {
  25. this.ctx.beginPath();
  26. for (var att in ops) this.ctx[att] = ops[att];
  27. dotXY = dotXY.constructor == Object ? [dotXY || { x: 0, y: 0}] : dotXY;
  28. this.ctx.moveTo(dotXY[0].x, dotXY[0].y);
  29. for (var i = 1, len = dotXY.length; i < len; i++) this.ctx.lineTo(dotXY[i].x, dotXY[i].y);
  30. this.ctx.stroke();
  31. };
  32. };
  33. window.onload=function(){
  34. var c1 = new MyCanvas();
  35. c1.drawLine([{ x: 10, y: 10 }, { x: 10, y: 200 }],{lineWidth:2,strokeStyle:'rgb(0,0,0)'});
  36. c1.drawLine([{ x: 11, y: 10 }, { x: 11, y: 200 }],{lineWidth:2,strokeStyle:'rgb(255,255,255)'});
  37. c1.drawLine([{ x: 100, y: 10 }, { x: 100, y: 200 }],{lineWidth:1,strokeStyle:'rgb(0,0,0)'}); //普通线
  38. c1.drawLine([{ x: 200.5, y: 10 }, { x: 200.5, y: 200 }],{lineWidth:1,strokeStyle:'rgb(0,0,0)'}); //+0.5偏移
  39. }
  40. </script>
  41. </head>
  42. <body>
  43. ↓ 处理的  ↓ 普通的  ↓ +0.5偏移的<br />
  44. </body>
  45. </html>

相关推荐:

HTML5 Canvas画线技巧——实现绘制一个像素宽的细线_html5教程技巧

以上就是Html5中Canvas画线有毛边如何解决的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行