编译原理的作业要求是输入正则式,转换成nfa、dfa、mfa后进行可视化。前面转换的数据逻辑部分就不赘述了,网络上有各种精巧的解法。考虑到需要可视化,就用js来写,毕竟html的canvas比c++的各种类库要方便许多。
写绘图逻辑部分内容的时候,也遇到了些许问题,其中就有绘制箭头、连接各个状态的直线的绘制等问题,这里就记录一下跟canvas操作有关的代码,以便之后查阅。(绘制箭头部分的代码显而易见不是最优解……)
function initCtx(ctx){
ctx.font="20px Georgia";
}
function drawCircle(ctx,circle) {
ctx.beginPath();
ctx.arc(circle.x,circle.y,circle.r,0,2*Math.PI);
ctx.stroke();
let title = circle.title === undefined ? "" : circle.title;
let _x = circle.x - ctx.measureText(title).width/2;
ctx.fillText(title,_x,circle.y);
}
function drawArrowLine(ctx,from,to,title=""){
let dis = Math.sqrt(Math.pow(from.x-to.x,2) + Math.pow(from.y-to.y,2));
let _cos = (to.x-from.x)/dis;
let _sin = (to.y-from.y)/dis;
let startx = from.x + from.r*_cos;
let starty = from.y + from.r*_sin;
let endx = to.x - to.r*_cos;
let endy = to.y - to.r*_sin;
drawLine(ctx,startx,starty,endx,endy);
drawArrow(ctx,startx,starty,end

这篇博客主要记录了如何利用HTML的Canvas API在JavaScript中实现NFA、DFA、MFA的可视化,特别关注了在画布上绘制箭头的逻辑,以连接不同状态。尽管绘制箭头的代码可能不是最优化的解决方案,但它是完成编译原理作业的一个实用方法。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



