dash-sanity.html (3536B)
1 <html> 2 <head> 3 <script type="text/javascript"> 4 function assert(cond, msg) { if (!cond) { throw msg; } } 5 window.onload = function() { 6 try { 7 var ctx = document.getElementById("c1").getContext("2d"); 8 9 assert(0 === ctx.getLineDash().length, 10 "Default dash is [ ] (none)"); 11 assert(0 === ctx.lineDashOffset, 12 "Default dashOffset is 0 (none)"); 13 14 ctx.setLineDash([ 2 ]); 15 assert(2 === ctx.getLineDash().length && 16 2 === ctx.getLineDash()[0] && 17 2 === ctx.getLineDash()[1], 18 "dash = [ 2 ] works"); 19 ctx.setLineDash([ 2 ]); 20 ctx.setLineDash([ ]); 21 assert(0 === ctx.getLineDash().length, 22 "dash = [ ] works"); 23 ctx.setLineDash([ 2 ]); 24 ctx.setLineDash([ 0, 0, 0 ]); 25 assert(6 === ctx.getLineDash().length, 26 0 === ctx.getLineDash()[0] && 27 0 === ctx.getLineDash()[1] && 28 0 === ctx.getLineDash()[2] && 29 0 === ctx.getLineDash()[3] && 30 0 === ctx.getLineDash()[4] && 31 0 === ctx.getLineDash()[5], 32 "dash = [ 0, 0, 0 ] works"); 33 34 ctx.setLineDash([ 2 ]); 35 assert(0 === ctx.lineDashOffset, "dashOffset is 0"); 36 ctx.lineDashOffset = 1; 37 assert(1 === ctx.lineDashOffset, "Setting dashOffset succeeded"); 38 ctx.setLineDash([ ]); 39 assert(1 === ctx.lineDashOffset, "Changing dash does not reset dashOffset"); 40 41 // NB: might want to add a |.dash = number| special case, 42 // don't test that it fails here. Might also want to add a 43 // |.dash = [0]| special case for resetting, so don't test 44 // that either. 45 var badVals = [ -1, 46 null, 47 undefined, 48 "", 49 "string", 50 { obj: true }, 51 function() {} 52 ] 53 ctx.setLineDash([ 2 ]); 54 for (var i = 0; i < badVals.length; ++i) { 55 var error = false; 56 try { ctx.setLineDash(badVals[i]); } 57 catch(e) { error = true; } 58 assert(error && 59 2 === ctx.getLineDash().length && 60 2 === ctx.getLineDash()[0] && 61 2 === ctx.getLineDash()[1], 62 "Expected setLineDash("+ badVals[i] +") to throw exception and not change dash"); 63 } 64 65 var ignoredVals = [ 66 [ "array of string" ], 67 [ -1 ], 68 [ 2, "string" ], 69 ]; 70 ctx.setLineDash([ 2 ]); 71 for (var i = 0; i < ignoredVals.length; ++i) { 72 ctx.setLineDash(ignoredVals[i]); 73 assert(2 === ctx.getLineDash().length && 74 2 === ctx.getLineDash()[0] && 75 2 === ctx.getLineDash()[1], 76 "Expected |setLineDash(" + ignoredVals[i] + ") to not change dash"); 77 } 78 79 ctx.setLineDash([ 2 ]); 80 ctx.save(); 81 ctx.setLineDash([ 1, 1, 1, 1 ]); 82 ctx.restore(); 83 assert(2 === ctx.getLineDash().length && 84 2 === ctx.getLineDash()[0] && 85 2 === ctx.getLineDash()[1], 86 "dash was saved then restored"); 87 } catch (e) { 88 document.body.innerHTML = "FAIL: "+ e.toString(); 89 return; 90 } 91 document.body.innerHTML = "Pass"; 92 } 93 </script> 94 </head> 95 <body> 96 <div><canvas id="c1" width="300" height="300"></canvas></div> 97 </body> 98 </html>