Interesting effect with the canvas element and CSS

Messages
5
Reaction score
0
Points
0
So I have a page with 2 canvas elements.

Used JS to draw a 10x10 rectangle to each canvas. And they looked correct.

Then resized the canvas elements with a css class using the width and height properties. Instead of pixles I used percentage. First canvas width 100% height 88%. Second canvas width 100% height 8%.

Without changing the js the squares are not the same size.


Weird eh?
 

lemon-tree

x10 Minion
Community Support
Messages
1,420
Reaction score
46
Points
48
This is because the canvas element only redraws itself when you specifically give it an instruction through JS and between these such requests it can be likened to a simple image element, so it behaves just is resizing an image would. This is done so that you can alter the canvas through simple CSS resizing and rotating etc without having to go back to the JS and redrawing it, thus making development an awful lot more efficient.
 
Messages
5
Reaction score
0
Points
0
Been a while been busy ...

From my css file
Code:
canvas.main
{
	width:100%;
	height:40%;
}

the canvas element
Code:
<canvas id="main" class="main" onClick="javascript:draw()">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>

And the script. Draw a red and blue rectangle with a width and height of 10 aka a square

Code:
function draw()
{
	var example = document.getElementById('main');
	var context = example.getContext('2d');
	context.fillStyle = "rgb(255,0,0)";
	context.fillRect(0, 0, 10, 10);
	context.fillStyle = "rgb(0,0,255)";
	context.fillRect(20, 20, 10, 10);
}

Result -- 2 rectangles not squares

If i change the canvas size to 100% 100% they are squares ... although not 10 px each. Tested in chrome and firefox
 

denzil

New Member
Messages
134
Reaction score
3
Points
0
I'm quite sure lemon-tree gave an accurate description of what's going on right above your reply!!
 
Messages
5
Reaction score
0
Points
0
The way he had stated it i if the canvas were drawn on THEN re-sized it would do that. I have the canvas sized then drawing on it.

By the way he had stated it:
Draw a 10x10 square
Resize canvas to 1/2 height or so
Square is now a rectangle that is 5x10

What I am pointing out:
Size a canvas to 1/2 height or so
Draw a 10x10 square
Square should still be 10x10 but is not
 

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
I get what you describe in Chrome, but not in FireFox. Firefox renders squares. Interestingly, the blue square has fuzzy edges and the bottom & right edges of the red square are fuzzy in Firefox.

If I resize the Chrome window, the images change proportions in the direction of the resize ... I can make the images square.

If I resize the Firefox window, the images change absolute size, but remain squares
 
Last edited:
Top