详解Html5 Canvas画线有毛边处理方式

2020-10-13 15:56 jianzhan

Html5 Canvas 全部的画线命令画出来的线条都有毛边(例如 lineTo, arcTo,strokeRect),这是由于在Canvas中整数金额座标值对应的部位正巧是显示屏象素点正中间的夹缝,那末当按这样的座标开展线条3D渲染时所要用到的便是夹缝两侧的象素点,这样就算设定了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⑻">  
    <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>  

以上便是本文的所有內容,期待对大伙儿的学习培训有一定的协助,也期待大伙儿多多适用脚本制作之家。