@@ -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 }
@@ -300,6 +301,23 @@ impl DrawingBackend for CanvasBackend {
300301 }
301302}
302303
304+ /// Move line coord to left/right half pixel if the line is vertical/horizontal
305+ /// to prevent line blurry in canvas, see https://stackoverflow.com/a/13879322/10651567
306+ /// and https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors#a_linewidth_example
307+ fn fine_hor_ver_lines ( from : BackendCoord , end : BackendCoord ) -> ( ( f64 , f64 ) , ( f64 , f64 ) ) {
308+ let mut from = ( from. 0 as f64 , from. 1 as f64 ) ;
309+ let mut end = ( end. 0 as f64 , end. 1 as f64 ) ;
310+ if from. 0 == end. 0 {
311+ from. 0 -= 0.5 ;
312+ end. 0 -= 0.5 ;
313+ }
314+ if from. 1 == end. 1 {
315+ from. 1 -= 0.5 ;
316+ end. 1 -= 0.5 ;
317+ }
318+ ( from, end)
319+ }
320+
303321#[ cfg( test) ]
304322mod test {
305323 use super :: * ;
@@ -533,4 +551,25 @@ mod test {
533551
534552 check_content ( & document, "test_draw_pixel_alphas" ) ;
535553 }
554+
555+ #[ test]
556+ fn test_fine_hor_ver_lines ( ) {
557+ // not horizontal nor vertical
558+ assert_eq ! (
559+ ( ( 10.0 , 10.0 ) , ( 20.0 , 20.0 ) ) ,
560+ fine_hor_ver_lines( ( 10.0 , 10.0 ) , ( 20.0 , 20.0 ) )
561+ ) ;
562+
563+ // vertical
564+ assert_eq ! (
565+ ( ( 9.5 , 10.0 ) , ( 19.5 , 10.0 ) ) ,
566+ fine_hor_ver_lines( ( 10.0 , 10.0 ) , ( 20.0 , 10.0 ) )
567+ ) ;
568+
569+ // horizontal
570+ assert_eq ! (
571+ ( ( 10.0 , 9.5 ) , ( 10.0 , 19.5 ) ) ,
572+ fine_hor_ver_lines( ( 10.0 , 10.0 ) , ( 10.0 , 20.0 ) )
573+ ) ;
574+ }
536575}
0 commit comments