1. 程式人生 > 程式設計 >JavaScript使用canvas繪製座標和線

JavaScript使用canvas繪製座標和線

本文例項為大家分享了javascript使用canvas繪製座標和線的具體程式碼,供大家參考,具體內容如下

具體程式碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>在指定位置畫多個點</title>
    <style>
        canvas{
            border: 1px dashed gray;
        }
    </style>
</head>
<body>
    <canvas id="cvs" width="500" height="500"></canvas>
</body>
</html>

js程式碼:

<script>
    var cvs = document.getElementById('cvs');
    var ctx = cvs.getContext('2d');
 
    // 座標軸距離畫布上右下左的邊距
 程式設計客棧   var padding = {
        top:20,right:20,bottom:20,left:20
    }
    // 座標軸中箭頭的寬和高
    var arrow = {
        width:12,height:20
    }
    // 求座標軸上頂點的座標
    var vertexTop = {
        x:padding.left,y:padding.top
    }
    // 求座標軸原點的座標
    var origin = {
        x:padding.left,y:cvs.height - padding.bottom
    }
    // 求座標軸右頂點的座標
    var vertexRight = {
        x:cvs.width - padding.left,y:cvs.height - padding.bottom
    }
 
    //設定線寬
 
程式設計客棧
ctx.lineWidth = 2; //畫座標軸的兩條線 ctx.beginPath(); ctx.moveTo(vertexTop.x,vertexTop.y); ctx.lineTo(origin.x,origin.y); ctx.lineTo(vertexRight.x,vertexRight.y); ctx.stroke(); //如何畫箭頭 //畫頂上箭頭 // ^ // | // | ctx.beginPath(); ctx.moveTo(vertexTop.x,vertexTop.y); ctx.lineTo(vertexTop.x - arrow.width/2,vertexTop.y + arrow.height); ctx.lineTo(vertexTop.x,vertexTop.y + arrow.height/2); ctx.lineTo(vertexTop.x + arrow.width/2,vertexTop.y + arrow.height); ctx.fill(); //畫右邊的箭頭 // ---> ctx.beginPath(); ctx.moveTo(vertexRight.x,vertexRight.y); ctx.lineTo(vertexRight.x - arrow.height,vertexRight.y - arrow.width); ctx.lineTo(vertexRight.x - arrow.hehttp://www.cppcns.com
ight/2,vertexRight.y + arrow.width); ctx.fill(); /* * 在座標軸中指定位置畫點,座標演算法: * 點的x軸:原點x座標 + 點到原點的水平距離 * 點的y軸:原點y座標 - 點到原點的垂直距離 */ //定義點的座標 var points = [[10,10],[50,50],[90,90],[130,130],[170,170],[200,200]]; //在座標中畫點 使用迴圈遍歷陣列中的座標 //設定顏色 ctx.fillStyle = "green"; points.forEach(function(arr){ ctx.fillRect(origin.x + arr[0],origin.y - arr[1],5,5); }http://www.cppcns.com); //根據點連線 //防止重繪 ctx.beginPath(); ctx.lineWidth = 2; ctx.strokeStyle = "yellow"; points.forEach(function (arr) { ctx.lineTo(origin.x + arr[0] + 1.8,origin.y - arr[1]lKYFws + 1.8); }); //描邊 ctx.stroke(); </script>

效果如下:

JavaScript使用canvas繪製座標和線

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。