Rectangle on HTML5 Canvas is stretched - javascript

I am working on a website and I try to get rectangles on a HTML5 canvas with javascript. Normally this is no problem but now when I make a rectangle with the width and height of 10. It seems that it makes a rectangle with the width of 10 and the height of 20.
I'm making the Rectangle like this:
var canvas = $("#canvas");
var context = canvas.get(0).getContext("2d");
context.fillRect(0, 0, 10, 10);
The div canvas is set with a width of 100% but i tried to give it a fixed width and that didn't help either.

You need to set a width and height on your canvas element, otherwise this can be the result in some browsers.
<canvas id="canvas" width="400" height="300" />
And you can not set the canvas size with CSS, this will stretch the canvas.

The default size of the canvas is 300 x 150.
You are probably using these defaults, which will make the rectangle look not square....

Related

How can i get high resolution image from smaller canvas?

I am using one canvas in my web app and it's actual height and width are 500px. I am showing this canvas on screen as 500px square but i want image exported from this canvas as 1600px square. I have tried below code with no luck.
canvas.width = 1600;
canvas.style.width = 500;
Any help will be appreciated.
You can have the canvas display at 500px while still having a resolution of 1600px. Display size and resolution are independent. For resolution you set the canvas width and height properties. For display size you set the canvas style width and height properties.
// create a canvas or get it from the page
var canvas = document.createElement("canvas");
// set the resolution (number of pixels)
canvas.width = canvas.height = 1600;
// set the display size
canvas.style.width = canvas.style.height = "500px";
// get the rendering context
var ctx = canvas.getContext("2d");
To get the rendering to match the display size you need to scale up all rendering. You can do this by setting the transform scale to the canvas resolution divided by the display size
var scale = 1600 / 500; // get the scale that matches display size
ctx.setTransform(scale,0,0,scale,0,0);
Now when you render to the canvas you use the screen size coordinates.
ctx.fillRect(0,0,500,500); // fill all of the canvas.
ctx.fillStyle = "red"; // draw a red circle 100 display pixels in size.
ctx.beginPath();
ctx.arc(250,250,100,0,Math.PI * 2);
ctx.fill();
When you then save the canvas, what ever method you use as long as it is not screen capture the saved canvas will be 1600 by 1600 and all the rendering will be correctly positions and proportional
HTML
<canvas width="1600px" height="1600px" > </canvas>
CSS
canvas{
position :absolute;
transform:scale(0.3125);
left:-500px; //adjust
top:-350px; //adjust
}
Use transform:scale() to adjust size of your canvas
Now 1600 * 1600 will be the actual size of your canvas, so you can directly export images from your canvas
But in view it show as 500px * 500px beacuse it's scaled down, it dose not affect the image quality while exporting
Honest answer: you can't.
If you did, then you'd have found a way to losslessly compress data with less than 1/9th of the original size, and without any encoding, which is unarguably impossible.
What you can do is scale it up in a way that it at least doesn't get blurry. To do that, you need the final image to be an integer multiple of the previous canvas, so the browser won't apply anti-aliasing. Or if you want to use your own copying formula with putImageData that would get rid of anti-aliasing, you'll still get various incongruences and it would be very slow
In your case, the closest you could get is 1500x1500 ( 3*500x3*500 ). If your point was to process an image, you're not in luck, but if you just want to display something good enough, you can resort to various other tricks such as centering the canvas and using properties like box-shadow to make it clear that it's separate from the rest of the screen

Why are my drawings sized relatively to the canvas size?

I have a canvas defined as
<canvas id="field"></canvas>
style.css:
canvas#field {
width: 500px;
height: 250px;
border: 3px solid black; /* for now */
}
Whenever I try drawing stuff on it, like
var ctx = field.getContext("2d")
// circle
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();
It always ends up being sized relatively to the canvas dimensions. If I make the canvas twice as big, the circle is also twice as big, even though my radius is always 50px. If I make my canvas a square, the circle becomes elongated downwards, and vice versa if I stretch the canvas out sideways.
How do I make the canvas treat the numbers I give it as absolute values?
You should set canvas width and height as HTML attributes instead of CSS rules:
<canvas id="field" width="500" height="250"></canvas>
Quoting MDN:
The <canvas> element has only two attributes, width and height. These are both optional and can also be set using DOM properties. When no width and height attributes are specified, the canvas will initially be 300 pixels wide and 150 pixels high. The element can be sized arbitrarily by CSS, but during rendering the image is scaled to fit its layout size: if the CSS sizing doesn't respect the ratio of the initial canvas, it will appear distorted.
You can also set width and height dynamically using JavaScript:
const canvas = document.querySelector('canvas');
canvas.width = '500';
canvas.height = '250';

Canvas behaves oddly at different sizes

Been playing around with canvas lately, but it behaves oddly at different sizes.
Here's my code:
HTML: <canvas></canvas>
CSS: canvas { width:300px; height:50px; }
JS:
var c = document.querySelector("canvas"),
ctx = c.getContext("2d");
ctx.fillRect(10,10,50,50); // fill a 50x50 square at pos (10,10)
At canvas size 300x50, the following is drawn:
At canvas size 100x200, the following is drawn:
It's clear that one pixel does not actually mean one pixel - am I doing something wrong?
Don't use CSS to change the size of the canvas. Instead change the size of the element:
c.width=300;
c.height=50;
That's because when you resize with CSS you're "stretching" the pixels. When you change the size of the element itself, you are actually adding/subtracting pixels.

javascript: how does canvas.drawImage work

I'm trying to draw an image onto a canvas, like this:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,0,0,100,100,0,0,200,200);
The canvas is 200px by 200px and the image is much bigger (but styled at 200px by 200px too)
As you can see in the jsfiddle the canvas doesn't show the image (I was expecting a part of the image).
My understanding of drawImage (as is described here) goes like this:
"0,0,100,100" defines a rectangle on the image which is the part that is drawn onto the canvas. 0,0 defines the top/left corner and 100,100 are the widths of the sides.
This rectangle is drawn onto the canvas inside the rectangle defined by 0,0,200,200
Any suggestions what goes wrong here ?
You image is actually 585 x 585 so what you are doing is to clip a corner from it (which is blank) and draw it onto canvas which of course won't show anything.
Scaling the image with CSS doesn't actually change its size. It only scales it for display.
So what you need to do is to use the original size of the image as basis. If you simply want to scale it down to fit in canvas you can do:
ctx.drawImage(img, 0, 0, 200, 200);
The same goes for canvas. Don't scale canvas using CSS but set the width and height properties/attributes or else the canvas will default to 300x150 (which is then scaled by your css):
<canvas width=200 height=200 ...>
Modified fiddle
Set the width and height on the canvas and draw the image at the same dimensions. Updated your fiddle - http://jsfiddle.net/FQhGg/2/
var c=document.getElementById("myCanvas"),
ctx=c.getContext("2d"),
img=document.getElementById("scream"),
width = img.width,
height = img.height;
c.width = width;
c.height = height;
ctx.drawImage(img,0,0,width,height);

HTML5 canvas stroke() thick and fuzzy

I'm trying to allow the user to draw a rectangle on the canvas (like a selection box). I'm getting some ridiculous results, but then I noticed that even just trying the code from my reference here, I get huge fuzzy lines and don't know why.
it's hosted at dylanstestserver.com/drawcss. the javascript is inline so you can check it out. I am using jQuery to simplify getting the mouse coordinates.
The blurry problem will happen if you use css to set the canvas height and width instead of setting height and width in the canvas element.
<style>
canvas { height: 800px; width: 1200px; } WRONG WAY -- BLURRY LINES
</style>
<canvas height="800" width="1200"></canvas> RIGHT WAY -- SHARP LINES
For some reason, your canvas is stretched. Because you have its css property width set to 100%, it is stretching it from some sort of native size. It's the difference between using the css width property and the width attribute on the <canvas> tag. You might want to try using a bit of javascript to make it fill the viewport (see jQuery .width()):
jQuery(document).ready(function(){
var canvas = document.getElementById('drawing');
canvas.width(($(window).width()).height($(window).height());
var context = canvas.getContext('2d');
//...
The way I do it is to set the canvas element to a width and height in the css, and then set the canvas.width = canvas.clientWidth and canvas.height = canvas.clientHeight
var canvas = document.getElementById("myCanvas");
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
var context = canvas.getContext("2d");
You haven't indicated canvas size in pixels, so it is scaled up. It is 300x150 here. Try setting the width, height
On retina displays you also need to scale (in addition to the accepted answer):
var context = canvas.getContext('2d');
context.scale(2,2);
The css sizing issue mentioned in these comments is correct, but another more subtle thing that can cause blurred lines is forgetting to call make a call to context.beginPath() before drawing a line. Without calling this, you will still get a line, but it won't be smoothed which makes the line looks like a series of steps.
I found the reason mine was blurry was that there was a slight discrepancy between the inline width and the CSS width.
I have both inline width/height parameters AND css width/height assigned to my canvas, because I need to keep its physical dimensions static, while increasing its inline dimensions for retina screens.
Check yours are the same if you have a situation like mine.

Categories