canvas畫圖--坐標定位
以畫矩形為例:
把canvas設置成和屏幕等寬等高,canvas的起點坐標(0,0)設置在左上角,
當你使用ctx.fillRect(10,10,100,100);ctx.fill();畫圖時,可以很准確的把這個矩形定位在屏幕中的坐標(10,10)上。
當時當你使用ctx.strokeRect(10,10,100,100)時,則位置發生偏移,偏移多少和矩形邊框的粗細有關。
似乎在canvas中,所有帶邊框的形狀定位都有這個問題。
造成這個原因的是筆觸,如下圖:綠色的border就是canvas繪制的,我們只能看到一半,灰色區域外面的都被遮住了,看不到的。

解決辦法,如下:(下面的辦法把繪制的矩形的真正寬度=border+設置的width(也就是內容區域),類似普通div的box-sizing:content-box;)
function CvsGraph(ctx){ this.ctx=ctx; } CvsGraph.prototype={ createRect:function(x,y,w,h,strokeWidth,strokeColor,fillColor){ if(typeof strokeWidth!=="undefined"&&strokeWidth!=="none"){ //如果有筆觸的話 //修改后,把筆觸的偏移量糾正過來了,和普通div的盒子模型一樣 //糾正后,內容寬度為設置的寬度w,外面的邊框的寬度另外計算,它的大小粗細只受筆觸大小的控制 x+=strokeWidth/2; y+=strokeWidth/2; w+=strokeWidth; h+=strokeWidth; if(typeof strokeColor==="undefined"||strokeColor==="none"){ strokeColor="#000"; } }else{ strokeWidth="none"; } if(typeof fillColor==="undefined"){ fillColor="none"; } this._createRect(x,y,w,h,strokeWidth,strokeColor,fillColor); }, _createRect:function(x,y,w,h,strokeWidth,strokeColor,fillColor){ this.ctx.beginPath(); this.ctx.moveTo(x,y); this.ctx.lineTo(x+w,y); this.ctx.lineTo(x+w,y+h); this.ctx.lineTo(x,y+h); this.ctx.lineTo(x,y); this.ctx.closePath(); if(fillColor!=="none"){ this.ctx.fillStyle=fillColor; this.ctx.fill(); } if(strokeWidth!=="none"){ this.ctx.lineWidth=strokeWidth; this.ctx.strokeStyle=strokeColor; this.ctx.stroke(); } } };
調用:
...... var ctx=cvs.getContext("2d"); var obj=new CvsGraph(ctx); obj.createRect(0,0,100,100,"none","#000",1);
