您好,登錄后才能下訂單哦!
Html5 Canvas 所有的畫線指令畫出來的線條都有毛邊(比如 lineTo,arcTo,strokeRect),這是因?yàn)樵贑anvas中整數(shù)坐標(biāo)值對應(yīng)的位置恰巧是屏幕象素點(diǎn)中間的夾縫,那么當(dāng)按這樣的坐標(biāo)進(jìn)行線條渲染時(shí)所要用到的就是夾縫兩邊的象素點(diǎn),這樣即便設(shè)置了lineWidth為1也將看到兩個(gè)象素效果的線條,解決方法原象素點(diǎn)+0.5進(jìn)行偏移。
下面是處理前后的效果比較:
<!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) { //序號、計(jì)數(shù) 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延時(shí)問題手動初始化對象 if (typeof G_vmlCanvasManager != "undefined") G_vmlCanvasManager.initElement(cvs); //2D畫布對象 this.ctx = cvs.getContext("2d"); /* * 繪制線條 * @ops JSON對象,可按實(shí)際支持屬性擴(kuò)展,示例: { 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>
以上就是Html5中Canvas畫線有毛邊應(yīng)該怎么解決的詳細(xì)內(nèi)容,更多請關(guān)注億速云其它相關(guān)文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。