当前位置: 移动技术网 > IT编程>网页制作>Html5 > 详解Html5 Canvas画线有毛边解决方法

详解Html5 Canvas画线有毛边解决方法

2019年07月25日  | 移动技术网IT编程  | 我要评论
这篇文章主要介绍了详解Html5 Canvas画线有毛边解决方法的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧... 18-03-01

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

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

<!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd">  
<html>  
<head>  
    <meta http-equiv="content-type" content="text/html; charset=utf-8">  
    <title>canvastest</title>  
    <script type="text/javascript" src="http://www.pyzy.net/demo/html5_cancas_js/excanvas.js"></script>  
    <script type="text/javascript">  
        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.onload=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偏移  
   
        }  
     
    </script>  
</head>  
<body>  
↓ 处理的  ↓ 普通的  ↓ +0.5偏移的<br />  
</body>  
</html>  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网