1. 程式人生 > 其它 >【Canvas】將螢幕座標系轉換成笛卡爾座標系

【Canvas】將螢幕座標系轉換成笛卡爾座標系

Canvas繪圖裡的座標系是左上角為原點,向右為X正向,向下為Y正向,這被稱為螢幕座標系;

如果繪製的內容和幾何無關,螢幕座標系倒也沒什麼,熟悉了也就好了;

但如果要重現幾何問題,那人工變換來變換去既傷腦筋,也沒必要。

我們可以在繪製之前將ctx變換好,程式碼如下:

    // 進行螢幕座標系到笛卡爾座標系的變換,原點移動到畫布中央,右方為X正向,上方為Y的正向
    context.translate(WIDTH/2,HEIGHT/2);
    context.rotate(getRad(180));
    context.scale(-1,1);

這個方法我在之前的博文https://www.cnblogs.com/heyang78/p/7591175.html

也提到過。

但當時的問題是,圖形必須和文字分開繪製,文字位置還需要單獨計算一遍,這又做了一番無用功。

今天我看到同是部落格園的網友“秋離”的函式,覺得很好。函式如下:

/**
 * 該片段實現文字反轉
 * @param {*} ctx 即context
 * @param {*} text 繪製文字
 * @param {*} x 笛卡爾座標系轉換之前可以正常顯示的X座標
 * @param {*} y 笛卡爾座標系轉換之前可以正常顯示的Y座標
 */
function rotateText(ctx,text,x,y){
    ctx.save();
    ctx.translate(x,y)
    ctx.rotate(getRad(180))
    ctx.scale(-1,1)
    ctx.fillText(text,0,0);
    ctx.restore();
}

原理是把倒置的文字再變換回去。

經過這樣兩重處理後,圖形文字都正常了,如圖:

另外我將canvas程式碼重新整理了一份模板,其中將座標系變換,文字變換、前景後景動畫繪製都細化好了,特此放在這裡方便大家:

<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
     <title>螢幕座標系到笛卡爾座標系的轉換</title>
     <style type="text/css">
     .centerlize{
        margin:0 auto;
        border:0px solid red;
        width:512px;height:512px;
     }

     </style>
    </head>

     <body onload="draw();">
        <div class="centerlize">
            <canvas id="myCanvas" width="512px" height="512px" style="border:1px dashed black;">
                出現文字表示您的瀏覽器還不支援HTML5
            </canvas>
        </div>
        
     </body>
</html>
<script type="text/javascript">
<!--
// 畫布寬度
const WIDTH=512;
// 畫布高度
const HEIGHT=512;

// 旋轉角
var alpha=0;    

//-------------------------------
// 開始繪製
//-------------------------------
function draw(){
    var canvas=document.getElementById('myCanvas');    
    canvas.width=WIDTH;
    canvas.height=HEIGHT;    

    context=canvas.getContext('2d');   
    
    // 進行螢幕座標系到笛卡爾座標系的變換,原點移動到畫布中央,右方為X正向,上方為Y的正向
    context.translate(WIDTH/2,HEIGHT/2);
    context.rotate(getRad(180));
    context.scale(-1,1);

    slot=new Slot();
    animate();
};

//-------------------------------
// 有條件執行動畫
//-------------------------------
function animate(){    
  
    slot.update(alpha);
    slot.paintBg(context);
    slot.paint(context);

    alpha+=0.5;

    if(alpha<2000){        
        window.requestAnimationFrame(animate);
    }
}

//-------------------------------
// 光闌物件
//-------------------------------
function Slot(){
    var obj=new Object;

    obj.alpha=0;

    // 更新內部變數alpha
    obj.update=function(alpha){
        this.alpha=alpha;
    };

    // 畫固定件
    obj.paintBg=function(ctx){
        // 清屏
        context.clearRect(-WIDTH/2,-HEIGHT/2,WIDTH,HEIGHT);

        let ax=200,ay=0;
        let bx=0,by=200;

        ctx.strokeStyle='black';
        ctx.beginPath();
        ctx.moveTo(0,0);
        ctx.lineTo(ax,ay);
        ctx.closePath();
        ctx.stroke();

        ctx.strokeStyle='black';
        ctx.beginPath();
        ctx.moveTo(0,0);
        ctx.lineTo(bx,by);
        ctx.closePath();
        ctx.stroke();

        ctx.stokeStyle='black';
        ctx.font = '10px "微軟雅黑"';          
        ctx.textBaseline = "bottom";            
        ctx.textAlign = "center";  
        
        drawText(ctx,'X正向',ax,ay);
        drawText(ctx,'Y正向',bx,by);
    };

    // 畫活動件
    obj.paint=function(ctx){
        
    };
    
    return obj;
}

//-------------------------------
// 角度得到弧度
//-------------------------------
function getRad(degree){
    return degree/180*Math.PI;
}

//-------------------------------
// 得到顏色
//-------------------------------
function getColor(index){
    var arr=["green","skyblue","purple","#aa0000",
             "orange","yellow","maroon","navy",
             "red","blue","lime","teal","fuchsia",
             "aqua","black"];

    if(index>arr.length){
        index=index % arr.length;
    }

    return arr[index];
}

//-------------------------------
// 在笛卡爾座標系中繪製文字
// 此函式是為防止螢幕座標系變成笛卡爾座標系後文字出現倒置
// 原作者為部落格園的秋離,出處為https://www.cnblogs.com/ScottQee/p/13359713.html
//-------------------------------
function drawText(ctx,text,x,y){
    ctx.save();
    ctx.translate(x,y)
    ctx.rotate(getRad(180))
    ctx.scale(-1,1)
    ctx.fillText(text,0,0);
    ctx.restore();
}
//-->
</script>

END