I've looked at the questions here and followed the answers but my canvas is still low resolution:
CSS:
#canvas {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
JS: Initialise Canvas (called once when page load and again on window resize)
function initCanvas() {
$('#canvas').width($(window).width());
$('#canvas').height($(window).height());
}
Drawing line with
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
Result
JSFiddle
You can see that the line appears low res. I would like a canvas that is full window but appears sharp.
NB: I use absolute position and z-index -1 for canvas because I would like it to appear behind anything else I later add on the page.
try this
<canvas id="canvas" width="500" height="500">
</canvas>
We can't set the width and height of the canvas element using css, since it won't get rendered properly as document says. You have to set its
or you have to use
function initCanvas() {
$('#canvas').attr("width",$(window).width());
$('#canvas').attr("height",$(window).height());
}
There are two separate width/height values for a canvas:
style
property or css. These dimensions are used for rendering the element within the document.width
and height
properties of the element. These dimensions are used for drawing on the canvas via its context.You are successfully resizing the element with jQuery's width()
and height()
methods, which are shorthand for changing element.style.width
and element.style.height
.
All you are missing is setting the canvas's area, which is a property of the canvas element. You can do this with jQuery's prop()
method:
$('#canvas').prop({
width: x,
height: y
});
Or, if you want to do it all at once:
var dimensions = {
width: x,
height: y
};
$('#canvas').css(dimensions).prop(dimensions);
And lastly, here is a fiddle
Demo http://jsfiddle.net/U5XrK/3/
Q: I would like a canvas that is full window but appears sharp.
A: Set the width and height of the canvas to be the same as the window's in canvas' initiation time:
// Draw on canvas
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
c.width = $(window).width(); // Add this to your code
c.height = $(window).height(); // Add this to your code
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
Canvas consists of a drawable region defined in HTML code with height and width attributes.
When you give a value to its CSS width/height - it is similar to doing the same thing to an IMG element - you are scaling it, rather than setting its actual dimensions.
So you should be setting the canvas' HTML attributes for the actual dimensions, instead of its CSS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With