温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在JavaScript中利用canvas绘制坐标和线

发布时间:2021-04-29 16:00:31 来源:亿速云 阅读:345 作者:Leah 栏目:开发技术

怎么在JavaScript中利用canvas绘制坐标和线?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

javascript是一种什么语言

javascript是一种动态类型、弱类型的语言,基于对象和事件驱动并具有相对安全性并广泛用于客户端网页开发的脚本语言,同时也是一种广泛用于客户端Web开发的脚本语言。它主要用来给HTML网页添加动态功能,现在JavaScript也可被用于网络服务器,如Node.js。

具体代码如下:

<!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.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]];
    //在坐标中画点 使用循环遍历数组中的坐标
    //设置颜色
    ctx.fillStyle = "green";
    points.forEach(function(arr){
        ctx.fillRect(origin.x + arr[0],origin.y - arr[1],5,5);
    });
    //根据点连线
    //防止重绘
    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>

效果如下:

怎么在JavaScript中利用canvas绘制坐标和线

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI