Canvas is stretched when using CSS but normal with `width` & `height` attributes
Asked Answered
M

9

222

I have 2 canvases, one uses HTML attributes width and height to size it, the other uses CSS:

<canvas id="compteur1" width="300" height="300" onmousedown="compteurClick(this.id);"></canvas>
<canvas id="compteur2" style="width: 300px; height: 300px;" onmousedown="compteurClick(this.id);"></canvas>

Compteur1 displays like it should, but not compteur2. The content is drawn using JavaScript on a 300x300 canvas.

Why is there a display difference?

alt text

Mariellamarielle answered 6/4, 2010 at 20:45 Comment(0)
E
248

It seems that the width and height attributes determine the width or height of the canvas’s coordinate system, whereas the CSS properties just determine the size of the box in which it will be shown.

This is explained in the HTML specification:

The canvas element has two attributes to control the size of the element’s bitmap: width and height. These attributes, when specified, must have values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The width attribute defaults to 300, and the height attribute defaults to 150.

Edmonds answered 6/4, 2010 at 21:16 Comment(5)
indeed.. I always thought direct attributes like "width" and "height" were deprecated in recent html versions..Mariellamarielle
Oh, apparently it's actually described rather well at whatwg.org/specs/web-apps/current-work/multipage/… (section #attr-canvas-width). The trouble is that I clicked on the wrong width before and went to the #dom-canvas-width section instead. Filed w3.org/Bugs/Public/show_bug.cgi?id=9469 about it.Edmonds
Having an API that looks-like but is fundamentally different to another (css width, height). Wow.Kinkajou
It's important to distinguish these for times when you want the internal coordinate system to be different. (ie for retina displays or 8bit style game)Bradski
This was really confusing. We where trying to set the width and the height in the css. Took us 2 days of hair pulling stress to find out about these 2 different interpretations about width and height. Just wow...Hartley
V
47

To set the width and height on a canvas, you may use:

canvasObject.setAttribute('width', '150');
canvasObject.setAttribute('height', '300');
Villalba answered 16/3, 2011 at 5:41 Comment(5)
+1 el.setAttribute('width', parseInt($el.css('width'))) did the trick, thanksFransen
What if I want my canvas to have a relative size? That is to say, how to mimic a width: 100%; css property?Smart
Great answer, but don't forget to add the canvasObject.setAttribute('height', '123') too!Ulu
I don't think you need to use .setAttribute() I've always used the .width and .height propertiesTeatime
Plain JavaScript (without jQuery) version using getComputedStyle: canvas.setAttribute('width', window.getComputedStyle(canvas, null).getPropertyValue("width"));. Repeat for the height.Merchantman
T
31

For <canvas> elements, the CSS rules for width and height set the actual size of the canvas element that will be drawn to the page. On the other hand, the HTML attributes of width and height set the size of the coordinate system or 'grid' that the canvas API will use.

For example, consider this (jsfiddle):

var ctx = document.getElementById('canvas1').getContext('2d');
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 30, 30);

var ctx2 = document.getElementById('canvas2').getContext('2d');
ctx2.fillStyle = "red";
ctx2.fillRect(10, 10, 30, 30);
canvas {
  border: 1px solid black;
}
<canvas id="canvas1" style="width: 50px; height: 100px;" height="50" width="100"></canvas>
<canvas id="canvas2" style="width: 100px; height: 100px;" height="50" width="100"></canvas>

Both have had the same thing drawn on them relative to the internal coordinates of the canvas element. But in the second canvas, the red rectangle will be twice as wide because the canvas as a whole is being stretched across a bigger area by the CSS rules.

Note: If the CSS rules for width and/or height aren't specified then the browser will use the HTML attributes to size the element such that 1 unit of these values equals 1px on the page. If these attributes aren't specified then they will default to a width of 300 and a height of 150.

Toe answered 29/9, 2013 at 14:41 Comment(0)
P
16

The canvas will be stretched if you set the width and height in your CSS. If you want to dynamically manipulate the dimension of the canvas you have to use JavaScript like so:

canvas = document.getElementById('canv');
canvas.setAttribute('width', '438');
canvas.setAttribute('height', '462');
Pondicherry answered 22/1, 2013 at 9:48 Comment(1)
Great! Thanks for this answer. I had to put canvas.setAttribute before canvas.getContext('2d') to avoid stretching of the image.Manis
O
3

Shannimal correction

var el = $('#mycanvas');
el.attr('width', parseInt(el.css('width')))
el.attr('height', parseInt(el.css('height')))
Ontine answered 21/11, 2015 at 11:47 Comment(0)
N
3

Canvas renders image by buffer, so when you specify the width and height HTML attributes the buffer size and length changes, but when you use CSS, the buffer's size is unchanged. Making the image stretched.

Using HTML sizing.

Size of canvas is changed -> buffer size is changed -> rendered

Using CSS sizing

Size of canvas is changed -> rendered

Since the buffer length is kept unchanged, when the context renders the image, the image is displayed in resized canvas (but rendered in unchanged buffer).

Necessity answered 30/9, 2021 at 12:12 Comment(0)
G
1

CSS sets the width and height of the canvas element so it affects the coordinate space leaving everything drawn skewed

Here's my way on how to set the width and height with Vanilla JavaScript

canvas.width = numberForWidth

canvas.height = numberForHeight
Guiltless answered 8/4, 2020 at 19:40 Comment(0)
R
-1

If you want a dynamic behaviour based on, e.g. CSS media queries, don't use canvas width and height attributes. Use CSS rules and then, before getting the canvas rendering context, assign to width and height attributes the CSS width and height styles:

var elem = document.getElementById("mycanvas");

elem.width = elem.style.width;
elem.height = elem.style.height;

var ctx1 = elem.getContext("2d");
...
Restharrow answered 25/1, 2016 at 19:43 Comment(2)
It's clear that a canvas will get a default coordinate size (300 x 150) if size is only specified in CSS. However, this suggestion doesn't work for me, but the solution below does.Deprivation
@PerLindberg - This solution works if you have defined a CSS width and height in pixels for the canvas element.Restharrow
S
-1

I believe CSS has much better machinery for specifying the size of the canvas and CSS must decide styling, not JavaScript or HTML. Having said that, setting width and height in HTML is important for working around the issue with canvas.

CSS has !important rule that allows to override other styling rules for the property, including those in HTML. Usually, its usage is frowned upon but here the use is a legitimate hack.

In Rust module for WebAssembly you can do the following:

fn update_buffer(canvas: &HtmlCanvasElement) {
    canvas.set_width(canvas.client_width() as u32);
    canvas.set_height(canvas.client_height() as u32);
}

//.. 
#[wasm_bindgen(start)]
pub fn start() -> Result<(), JsValue> {
    // ...
    let canvas: Rc<_> = document
        .query_selector("canvas")
        .unwrap()
        .unwrap()
        .dyn_into::<HtmlCanvasElement>()
        .unwrap()
        .into();
    update_buffer(&canvas);
    // ...

    // create resizing handler for window
    {
        let on_resize = Closure::<dyn FnMut(_)>::new(move |_event: Event| {
            let canvas = canvas.clone();
            // ...

            update_buffer(&canvas);
            // ...
        window.add_event_listener_with_callback("resize", on_resize.as_ref().unchecked_ref())?;
        on_resize.forget();
    }
}

There we update the canvas buffer once the WASM module is loaded and then whenever the window is resized. We do it by manually specifying width and height of canvas as values of clientWidth and clientHeight. Maybe there are better ways to update the buffer but I believe this solution is better than those suggested by @SamB, @CoderNaveed, @Anthony Gedeon, @Bluerain, @Ben Jackson, @Manolo, @XaviGuardia, @Russel Harkins, and @fermar because

  1. The element is styled by CSS, not HTML.
  2. Unlike elem.style.width & elem.style.height trick used by @Manolo or its JQuery equivalent used by @XaviGuardia, it will work for canvas whose size is specified by usage as flex or grid item.
  3. Unlike the solution by @Russel Harkings, this also handles resizing. Though I like his answer because it is really clean and easy.
  4. WASM is the future! Haha :D

P.S. there's a ton of .unwrap() because Rust explicitly handles possible failures.

P.P.S.

    {
        let on_resize = Closure::<dyn FnMut(_)>::new(move |_event: Event| {
            let canvas = canvas.clone();
            // ...

            update_buffer(&canvas);
            // ...
        window.add_event_listener_with_callback("resize", on_resize.as_ref().unchecked_ref())?;
        on_resize.forget();
    }

can be done much cleaner with better libraries. E.g.

add_resize_handler(&window, move |e: ResizeEvent| {
  let canvas = canvas.clone();
  // ...

  update_buffer(&canvas);
})
Somnambulism answered 6/11, 2022 at 0:40 Comment(1)
There's no need to use Rust/WASM to explain a simple HTML/CSS concept.Andris

© 2022 - 2024 — McMap. All rights reserved.