首頁 > web前端 > H5教程 > 主體

Html5中Canvas畫線有毛邊如何解決

小云云
發布: 2018-03-03 10:16:52
原創
2335 人瀏覽過

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:&#39;rgb(255,255,255)&#39; }        
            * @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:&#39;rgb(0,0,0)&#39;});  
            c1.drawLine([{ x: 11, y: 10 }, { x: 11, y: 200 }],{lineWidth:2,strokeStyle:&#39;rgb(255,255,255)&#39;});  
            c1.drawLine([{ x: 100, y: 10 }, { x: 100, y: 200 }],{lineWidth:1,strokeStyle:&#39;rgb(0,0,0)&#39;}); //普通线  
            c1.drawLine([{ x: 200.5, y: 10 }, { x: 200.5, y: 200 }],{lineWidth:1,strokeStyle:&#39;rgb(0,0,0)&#39;}); //+0.5偏移  
   
        }  
     
    </script>  
</head>  
<body>  
↓ 处理的  ↓ 普通的  ↓ +0.5偏移的<br />  
</body>  
</html>
登入後複製

#相關建議:

HTML5 Canvas畫線技巧——實作繪製一個像素寬的細線_html5教學技巧

以上是Html5中Canvas畫線有毛邊如何解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!