+ 1
getContext("2d") property for canvas isn't working here. What to do instead? Please help!😞
8 Respuestas
+ 5
Well that's because the shape of your device screen isn't square.
For other one if you want to increase its dimensions using js just add the value with pixels.
let width = canvas.width;
width += 50+"px";
or just remove the px in the HTML and let it be 400
then you can simply add it.
+ 3
For making it circular remove the height and width from #canvas in css and add that in the HTML like :
<canvas id="canvas" height = "400" width = "400"></canvas>
it can be any value though that's just an example.
+ 3
@Shashi Ranjan
The reason is that in case of canvas when assigning dimensions , HTML and CSS play quite different roles. When you set it as HTML then it makes it as it's fixed dimension and anything that you draw inside it works just like it's meant to be whilst on the other hand if you add that in CSS it will not assign it a fixed dimension but rather will modify the existing one this ultimately resulting in non uniform point distribution and hence it makes the shape deformed.
+ 2
The problem here, is that, when the code is executed, the DOM (document) hasn't finished loading, so the element canvas is null, empty, doesn't exist.
To solve this you gotta do what you did, but inside a function that is called when the DOM loads, here an example:
window.onload = function()
{
var canvas = document....ById("MyCanvas");
canvas.getContext("2d");
}
this way, the code executes when the DOM is fully loaded, and you'll have no trouble for non-loaded elements.
+ 1
@noname Thank you so much!😄 It worked! but instead of circular it got elliptical...lol. I need to fix this.😉
+ 1
@Atrikant Thanks bro it worked! But what's the reason... those are CSS properties aren't they?
+ 1
@Atikrant got it! Now please just see that again. Even if the height and width both are 400px but in the output width gets much more than the assigned value. Also the dimension is not changing by further increment in both.
+ 1
yay! Got it!! Thanks😄😊