JavaScript使用canvas繪制坐標和線
更新時間:2021年04月28日 15:06:47 作者:evan_qb
這篇文章主要為大家詳細介紹了JavaScript使用canvas繪制坐標和線,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了JavaScript使用canvas繪制坐標和線的具體代碼,供大家參考,具體內(nèi)容如下
具體代碼如下:
<!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
}
//設(shè)置線寬
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.height/2,vertexRight.y);
ctx.lineTo(vertexRight.x - arrow.height,vertexRight.y + arrow.width);
ctx.fill();
/*
* 在坐標軸中指定位置畫點,坐標算法:
* 點的x軸:原點x坐標 + 點到原點的水平距離
* 點的y軸:原點y坐標 - 點到原點的垂直距離
*/
//定義點的坐標
var points = [[10,10],[50,50],[90,90],[130,130],[170,170],[200,200]];
//在坐標中畫點 使用循環(huán)遍歷數(shù)組中的坐標
//設(shè)置顏色
ctx.fillStyle = "green";
points.forEach(function(arr){
ctx.fillRect(origin.x + arr[0],origin.y - arr[1],5,5);
});
//根據(jù)點連線
//防止重繪
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = "yellow";
points.forEach(function (arr) {
ctx.lineTo(origin.x + arr[0] + 1.8,origin.y - arr[1] + 1.8);
});
//描邊
ctx.stroke();
</script>
效果如下:

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JS實現(xiàn)左右拖動改變內(nèi)容顯示區(qū)域大小的方法
這篇文章主要介紹了JS實現(xiàn)左右拖動改變內(nèi)容顯示區(qū)域大小的方法,涉及JavaScript實時響應鼠標事件動態(tài)改變頁面元素屬性的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-10-10
小程序異步問題之多個網(wǎng)絡請求依次執(zhí)行并依次收集請求結(jié)果
這篇文章主要介紹了小程序異步問題之多個網(wǎng)絡請求依次執(zhí)行并依次收集請求結(jié)果,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05

