이 콘텐츠는 한국어로 제공되지 않아 영어 버전으로 표시됩니다.

setLineDash method

Sets the current line dash pattern. The argument is a even numbered list of distances to alternately produce a line and a space.

HTML Canvas 2D Context level 2IE11




dashList [in]

Type: sequence

Array of lines and spaces in pixels for the dash pattern.

Return value

This method does not return a value.

Standards information


If the line dash pattern has an odd number of values, it is ignored.


This example shows a simple "marching ants" style borders around three rectangles. The setLineDash method sets up the initial pattern using the dashList array. The dashList array defines two lines, 12 and 3 pixels long, separated by 3 pixels. The lineDashOffset property is incremented and applied to the dashed lines. The offset is reset to 0 when it passes a value of the total of the lines and spaces in the dashList. This lets the pattern to move through a complete sequence before a reset, creating a smooth movement. See the example in action.

<!DOCTYPE html>
    <title>Dash line example</title>
    <canvas id="MyCanvas" width="500" height="400">This browser or document mode doesn't support canvas</canvas> 

     var dashList = [12, 3, 3, 3];  // Create a dot/dash sequence
     var antOffset = 0;  // Starting offset value

     function draw() {
       var canvas = document.getElementById("MyCanvas");
       if (canvas.getContext) {
         var ctx = canvas.getContext("2d");
         ctx.clearRect(0, 0, canvas.width, canvas.height);
         if (ctx.setLineDash) {
           //  Assign the dashList for the dash sequence
           //  Get the current offset 
           ctx.lineDashOffset = antOffset;  // To animate the lines
           ctx.lineJoin = "round";
           ctx.lineWidth = "3";
           ctx.strokeStyle = "blue";
           ctx.strokeRect(5, 5, 300, 250);
           ctx.strokeStyle = "red";
           ctx.strokeRect(150, 200, 300, 150);
           ctx.lineDashOffset = -antOffset;  // Reverse animation
           ctx.lineWidth = "7";
           ctx.strokeStyle = "green";
           ctx.strokeRect(250, 50, 150, 250);
         } else {
           ctx.font = "italic 200 36px/2 Unknown Font, sans-serif";
           ctx.fillStyle = "blue";
           ctx.fillText("Dashed lines aren't supported", 10, 100);

     //  Marching Ant code     
     function doAnts() {
       if (antOffset > 20)  // Reset offset after total of dash List values
           antOffset = 0;
       setTimeout(doAnts, 10);  //  Set a leisurely march of 10ms               
      doAnts();  //  Start the demo 

See also




© 2014 Microsoft