用Canvas绘制2D平面近大远小的马路斑马线

用Canvas绘制2D平面近大远小的马路斑马线

设置canvas和上下文:

首先,你需要创建一个元素,并获取其2D渲染上下文。

绘制斑马线:

使用fillRect或strokeRect方法绘制斑马线。你可以通过循环和计算来绘制多条具有不同宽度和间隔的斑马线。

添加道路背景(可选):

为了增加效果,你还可以绘制一个道路背景,比如灰色或沥青色。

代码

HTML

html 复制代码
<canvas id="myCanvas" width="1960" height="1080"></canvas> 

JavaScript

javascript 复制代码
const canvas = document.getElementById('myCanvas');  
const ctx = canvas.getContext('2d');  
// 定义马路人行道和斑马线属性变量  
const sidewalkLength = 800; // 30米,按100像素/米计算  
const sidewalkWidth = 1000; // 人行道宽度  
const sidewalkColor = '#808080'; // 人行道颜色
const banmaWidth = 20;
const banmaLength = 300;
const banmaGap = 15;
// 绘制马路
ctx.fillStyle = sidewalkColor;  
ctx.fillRect(0, 0, sidewalkLength, sidewalkWidth);
ctx.save();
// 绘制人行道 
ctx.translate(350, 0);
ctx.rotate(Math.PI/2);
ctx.fillStyle = 'white';
for (let i = 0; i * banmaWidth < sidewalkLength; i ++) {
  ctx.fillRect((banmaWidth + banmaWidth + i * 2 ) * i, -i * 2.5, banmaWidth + i * 2, banmaLength + i * 5);
}
ctx.restore();
ctx.font = "15px serif";
ctx.strokeText("模拟近大远小的斑马线", 450, 300);

效果

相关推荐
紫微AI18 分钟前
WebMCP:开启 Agentic Web 新时代——Chrome 新 API 的特性与前瞻
前端·chrome
恋猫de小郭7 小时前
AGENTS.md 真的对 AI Coding 有用吗?或许在此之前你没用对?
前端·人工智能·ai编程
sunny_9 小时前
构建工具的第三次革命:从 Rollup 到 Rust Bundler,我是如何设计 robuild 的
前端·rust·前端工程化
rfidunion9 小时前
springboot+VUE+部署(12。Nginx和前端配置遇到的问题)
前端·vue.js·spring boot
珹洺10 小时前
Java-servlet(五)手把手教你利用Servlet配置HTML请求与相应
java·运维·服务器·前端·servlet·html·maven
FYKJ_201010 小时前
springboot大学校园论坛管理系统--附源码42669
java·javascript·spring boot·python·spark·django·php
QQ243919710 小时前
语言在线考试与学习交流网页平台信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·spring boot·sql·学习·java-ee
范特西.i10 小时前
QT聊天项目(6)
前端
a11177611 小时前
水体渲染系统(html开源)
前端·开源·threejs·水体渲染
程序员小李白11 小时前
CSS 盒子模型
前端·css·html