Skip to content

Commit bb2f4fd

Browse files
authored
Merge pull request #10 from redforks/my
Prevent hort/vert line blur
2 parents f7bea41 + 2a5521f commit bb2f4fd

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "plotters-canvas"
3-
version = "0.3.0"
3+
version = "0.3.1"
44
authors = ["Hao Hou <[email protected]>"]
55
edition = "2018"
66
license = "MIT"

src/canvas.rs

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -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)]
304322
mod 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

Comments
 (0)