canvas 绘制文字

<canvas width="600px" height="400px"></canvas>
<script>
    var myCanvas = document.querySelector("canvas");
    var ctx = myCanvas.getContext("2d");
    var canvasHeight = ctx.canvas.height;
    var canvasWidth = ctx.canvas.width;
    ctx.moveTo(0,ctx.canvas.height/2);
    ctx.lineTo(ctx.canvas.width,ctx.canvas.height/2);
    ctx.moveTo(ctx.canvas.width/2,0);
    ctx.lineTo(ctx.canvas.width/2,ctx.canvas.height);
    ctx.strokeStyle="#ccc";
    ctx.stroke();
    //放文字
    ctx.beginPath();
    ctx.strokeStyle="black";
    //设置字体
    ctx.font="40px Microsoft YaHei";
    var str="你好啊,我是zq";
    //绘制文本
    //设置文字的位置,可以是center left right end默认start。。是相对于起始坐标来说的
    ctx.textAlign="center";
    //设置文字的基线对齐方式
    ctx.textBaseline="middle";

    //在文字底下划线
    //先获取线的起始点
    //获取文字的宽度,文字的高度已知,为40
    var textWidth=ctx.measureText(str).width;
    ctx.moveTo(canvasWidth/2-textWidth/2,canvasHeight/2+20);
    ctx.lineTo(canvasWidth/2+textWidth/2,canvasHeight/2+20);
    ctx.stroke();
    
    //字是空心的。。。。文字,起点位置。。起点位置默认在文字的左下角
    //ctx.strokeText(str,ctx.canvas.width/2,ctx.canvas.height/2);
    //字是实心的
    ctx.fillText(str,ctx.canvas.width/2,ctx.canvas.height/2);

</script>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值