您的当前位置:首页正文

用canvas画虚线

来源:华拓网

今天的任务是用canvas画小时候练字用的田字格,一般的田字格是虚线。
事先知道canvas里有setLineDash这么个api,测试结果是,
ios统统画的出,android里的chrome画的出,android里的微信浏览器画不出。于是否定掉。

function drawDashLine(ctx, x1, y1, x2, y2, dashLength){
      var dashLen = dashLength === undefined ? 5 : dashLength,
      xpos = x2 - x1, //得到横向的宽度;
      ypos = y2 - y1, //得到纵向的高度;
      numDashes = Math.floor(Math.sqrt(xpos * xpos + ypos * ypos) / dashLen); 
      //利用正切获取斜边的长度除以虚线长度,得到要分为多少段;
      for(var i=0; i<numDashes; i++){
         if(i % 2 === 0){
             ctx.moveTo(x1 + (xpos/numDashes) * i, y1 + (ypos/numDashes) * i); 
             //有了横向宽度和多少段,得出每一段是多长,起点 + 每段长度 * i = 要绘制的起点;
          }else{
              ctx.lineTo(x1 + (xpos/numDashes) * i, y1 + (ypos/numDashes) * i);
          }
       }
      ctx.stroke();
    }

野性十足的原生。