云切图

HTML

HTML标签复习,帮你快速掌握html标签,助推学生快速完成网页作业

首页 > 前端笔记 > HTML

html中canvas标签画网格及坐标系?dw网页制作

作者:admin 发布时间:2023-02-22 点击数:

无论您是新手,还是老手,本教程都值得一读。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas画网格坐标系</title>
<style>#canvas{border:1px solid #000;}</style>
<script type="text/javascript">
window.onload = function(){
    var canvasEl = document.getElementById('canvas');
    var context = canvasEl.getContext('2d');
     
    // 画一个表格, 得思考,每个格子多大!
    var space = 20;
    
    // 1:得到 画布的宽和高
    var cWidth = canvasEl.width;
    var cHeight = canvasEl.height;
    
    
    var rows = Math.floor(cHeight/space);
    var cols = Math.floor(cWidth/space);
    
    // 画横线 rows
    for(let i = 0; i< rows; i++){
    context.beginPath()
    context.moveTo(0,space*i-0.5);
    context.lineTo(cWidth,space*i-0.5);
    context.strokeStyle='#aaa';
    context.stroke();
    }
    
    // 画竖线 cols
    for(let j = 0; j < cols; j++){
    context.beginPath();
    context.moveTo(space*j-0.5,0);
    context.lineTo(space*j-0.5,cHeight);
    context.strokeStyle="#aaa";
    context.stroke();
    }
    
    // 画坐标线条
    var everPadding = 40; //(坐标离 网格边界的上下左右的距离!)
    
    // 起点
    var x = everPadding;
    var y = cHeight - everPadding
    
    // 终点:
    var x1 = cWidth-everPadding; 
       
    // X轴
    context.beginPath();
    context.moveTo(x,y);
    context.lineTo(x1,y);
    context.lineTo(x1-space,y-space);
    context.lineTo(x1-space,y+space);
    context.lineTo(x1,y);
    context.strokeStyle="red";
    context.fillStyle="red";
    context.stroke();
    context.fill();
    
    // Y轴
    context.beginPath();
    context.moveTo(x,y);
    context.lineTo(x,everPadding);
    context.lineTo(x-space,everPadding+space);
    context.lineTo(x+space,everPadding+space);
    context.lineTo(x,everPadding);
    context.strokeStyle="red";
    context.fillStyle="red";
    context.stroke();
    context.fill();
}
</script>
</head>
<body>
    <canvas id="canvas" width="500" height="500"></canvas>
</body>
</html>

以上代码运行效果如下:

1.jpg

关注我们共同进步

  • 扣扣交流群

  • 微信公众号

  • 私技术顾问

标签:

html canvas
嘿,我来帮您!