Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved canvas size getter to support high-dpi #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ backup/*
examples/wasm-demo/www/pkg
examples/.ipynb_checkpoints/
tarpaulin-report.html
.vscode/*
.vscode/*
.idea/
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ wasm-bindgen = "0.2.55"

[dependencies.web-sys]
version = "0.3.32"
features = ['Document', 'DomRect', 'Element', 'HtmlElement', 'Node', 'Window', 'HtmlCanvasElement', 'CanvasRenderingContext2d']
features = ['Document', 'DomRect', 'Element', 'HtmlElement', 'Node', 'Window', 'HtmlCanvasElement', 'CanvasRenderingContext2d', 'CssStyleDeclaration']

[dev-dependencies]
plotters = "^0.3.0"
Expand Down
9 changes: 8 additions & 1 deletion src/canvas.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::str::FromStr;
use js_sys::JSON;
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{window, CanvasRenderingContext2d, HtmlCanvasElement};
Expand Down Expand Up @@ -80,7 +81,13 @@ impl DrawingBackend for CanvasBackend {
type ErrorType = CanvasError;

fn get_size(&self) -> (u32, u32) {
(self.canvas.width(), self.canvas.height())
let style = window().unwrap()
.get_computed_style(&self.canvas)
.unwrap().unwrap();
let width = style.get_property_value("width").unwrap().replace("px", "");
let height = style.get_property_value("height").unwrap().replace("px", "");
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here we can handle it better if the CSS uses a different unit, like pt or rem.
Also, error handlings can be improved.

Please let me know if there is an interest in merging the pull request, then I will improve it further. Otherwise, this code is good enough for my use case at the moment.

(u32::from_str(&width).unwrap(),
u32::from_str(&height).unwrap())
}

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