Home > Web Front-end > JS Tutorial > body text

Use trigonometric functions to draw dotted lines on canvas

小云云
Release: 2018-01-13 11:21:17
Original
1270 people have browsed it

This article mainly introduces the relevant information on the method of drawing dotted lines on canvas using trigonometric functions. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Because the canvas api does not have dotted lines

, so you need to implement it yourself

Wouldn’t it be nice to review trigonometric functions by the way

var context=document.getElementById("canvas").getContext("2d");
function drawDashedLine(context,x1,y1,x2,y2,dashlength){
    dashlength=dashlength===undefined?5:dashlength;
    var deltaX=x2-x1; //一条直角边的长
    var deltay=y2-y1; //另一条指教边的长

    var numDashes=Math.floor(
        Math.sqrt(deltaX*deltaX+deltay*deltay)/dashlength  //Math.sqrt返回一个数的平方根  dashlength虚线每个点的长度
    )

    var everydashLength_x=deltaX/numDashes  //确定X轴每条虚线点的起始点
    var everydashLength_y=deltay/numDashes  //确定Y轴每条虚线点的起始点

    for(var i=0;i<numDashes;i++){
        context[i%2===0?&#39;moveTo&#39;:"lineTo"]
        (x1+everydashLength_x*i,y1+everydashLength_y*i)
    }
    context.stroke()

}
context.lineWidth=3
context.strokeStyle="blue"
drawDashedLine(context,20,20,context.canvas.width-20,20,20)
Copy after login

The effect is as shown

Related recommendations:

html Steps to implement dotted border lines

How to use Canvas to draw dotted lines

Summary of methods for setting dotted line style in html and css

The above is the detailed content of Use trigonometric functions to draw dotted lines on canvas. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template