Este contenido no se encuentra disponible en su idioma, pero aquí tiene la versión en inglés.

lineDashOffset property

Sets or gets the phase offset of the current line dash pattern. Can be changed to produce "marching ants" animation like marching ants.

This property is read/write.

HTML Canvas 2D Context level 2IE11



context.lineDashOffset = offsetInPixels; 
offsetInPixels = context.lineDashOffset;

Property values

Type: number

Offset in pixels to move dash pattern.

Standards information


Non-finite values (NaN, infinite) are ignored.

This property can be used to produce "marching ants" line movement as shown in the following example.


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. The Dash list value is set to a negative number for the last rectangle to reverse the animation. 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




© 2015 Microsoft