@@ -117,10 +117,11 @@ impl DrawingBackend for CanvasBackend {
117117 return Ok ( ( ) ) ;
118118 }
119119
120+ let ( from, to) = fine_hor_ver_lines ( from, to) ;
120121 self . set_line_style ( style) ;
121122 self . context . begin_path ( ) ;
122- self . context . move_to ( f64 :: from ( from . 0 ) , f64 :: from ( from . 1 ) ) ;
123- self . context . line_to ( f64 :: from ( to. 0 ) , f64 :: from ( to. 1 ) ) ;
123+ self . context . move_to ( from. 0 , from. 1 ) ;
124+ self . context . line_to ( to. 0 , to. 1 ) ;
124125 self . context . stroke ( ) ;
125126 Ok ( ( ) )
126127 }
@@ -299,6 +300,23 @@ impl DrawingBackend for CanvasBackend {
299300 }
300301}
301302
303+ /// Move line coord to left/right half pixel if the line is vertical/horizontal
304+ /// to prevent line blurry in canvas, see https://stackoverflow.com/a/13879322/10651567
305+ /// and https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors#a_linewidth_example
306+ fn fine_hor_ver_lines ( from : BackendCoord , end : BackendCoord ) -> ( ( f64 , f64 ) , ( f64 , f64 ) ) {
307+ let mut from = ( from. 0 as f64 , from. 1 as f64 ) ;
308+ let mut end = ( end. 0 as f64 , end. 1 as f64 ) ;
309+ if from. 0 == end. 0 {
310+ from. 0 -= 0.5 ;
311+ end. 0 -= 0.5 ;
312+ }
313+ if from. 1 == end. 1 {
314+ from. 1 -= 0.5 ;
315+ end. 1 -= 0.5 ;
316+ }
317+ ( from, end)
318+ }
319+
302320#[ cfg( test) ]
303321mod test {
304322 use super :: * ;
@@ -532,4 +550,25 @@ mod test {
532550
533551 check_content ( & document, "test_draw_pixel_alphas" ) ;
534552 }
553+
554+ #[ test]
555+ fn test_fine_hor_ver_lines ( ) {
556+ // not horizontal nor vertical
557+ assert_eq ! (
558+ ( ( 10.0 , 10.0 ) , ( 20.0 , 20.0 ) ) ,
559+ fine_hor_ver_lines( ( 10.0 , 10.0 ) , ( 20.0 , 20.0 ) )
560+ ) ;
561+
562+ // vertical
563+ assert_eq ! (
564+ ( ( 9.5 , 10.0 ) , ( 19.5 , 10.0 ) ) ,
565+ fine_hor_ver_lines( ( 10.0 , 10.0 ) , ( 20.0 , 10.0 ) )
566+ ) ;
567+
568+ // horizontal
569+ assert_eq ! (
570+ ( ( 10.0 , 9.5 ) , ( 10.0 , 19.5 ) ) ,
571+ fine_hor_ver_lines( ( 10.0 , 10.0 ) , ( 10.0 , 20.0 ) )
572+ ) ;
573+ }
535574}
0 commit comments