Skip to content

Commit c2d7c8f

Browse files
committed
Fix the CanvasBackend size bug
1 parent 4c63766 commit c2d7c8f

File tree

4 files changed

+9
-13
lines changed

4 files changed

+9
-13
lines changed

examples/wasm-demo/src/func_plot.rs

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ pub fn draw(canvas_id: &str, power: i32) -> DrawResult<impl Fn((i32, i32)) -> Op
1010
root.fill(&WHITE)?;
1111

1212
let mut chart = ChartBuilder::on(&root)
13+
.margin(20)
1314
.caption(format!("y=x^{}", power), font)
1415
.x_label_area_size(30)
1516
.y_label_area_size(30)

examples/wasm-demo/www/index.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
<main>
1313
<h1>Plotters WebAssembly Demo</h1>
1414
<div id="coord"></div>
15-
<canvas id="canvas" width="600" height="400"></canvas>
15+
<canvas id="canvas" width="600" height="400"></canvas>
1616
<div id="status">Loading WebAssembly...</div>
1717
<div id="control">
1818
<label for="plot-type">Demo: </label>

examples/wasm-demo/www/index.js

+6-7
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,13 @@ function setupUI() {
3030

3131
/** Setup canvas to properly handle high DPI and redraw current plot. */
3232
function setupCanvas() {
33-
const dpr = window.devicePixelRatio || 1;
33+
const dpr = window.devicePixelRatio || 1.0;
3434
const aspectRatio = canvas.width / canvas.height;
35-
const size = Math.min(canvas.width, canvas.parentNode.offsetWidth);
36-
canvas.style.width = size + "px";
37-
canvas.style.height = size / aspectRatio + "px";
38-
canvas.width = size * dpr;
39-
canvas.height = size / aspectRatio * dpr;
40-
canvas.getContext("2d").scale(dpr, dpr);
35+
const size = canvas.parentNode.offsetWidth * 0.8;
36+
canvas.style.width = size * dpr + "px";
37+
canvas.style.height = size * dpr / aspectRatio + "px";
38+
canvas.width = size;
39+
canvas.height = size / aspectRatio;
4140
updatePlot();
4241
}
4342

src/drawing/backend_impl/canvas.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,8 @@ impl DrawingBackend for CanvasBackend {
7373
type ErrorType = CanvasError;
7474

7575
fn get_size(&self) -> (u32, u32) {
76-
// Getting just canvas.width gives poor results on HighDPI screens.
7776
let window = window().unwrap();
78-
let mut dpr = window.device_pixel_ratio();
79-
dpr = if dpr == 0.0 { 1.0 } else { dpr };
80-
((self.canvas.width() as f64 / dpr) as u32,
81-
(self.canvas.height() as f64 / dpr) as u32)
77+
(self.canvas.width(), self.canvas.height())
8278
}
8379

8480
fn ensure_prepared(&mut self) -> Result<(), DrawingErrorKind<CanvasError>> {

0 commit comments

Comments
 (0)