+ 1

getContext("2d") property for canvas isn't working here. What to do instead? Please help!😞

https://code.sololearn.com/Wlnts6nhnrrO/?ref=app

5th Mar 2018, 4:44 AM
Шащи Ранжан
Шащи Ранжан - avatar
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.
5th Mar 2018, 5:33 AM
RZK 022
RZK 022 - avatar
+ 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.
5th Mar 2018, 5:15 AM
RZK 022
RZK 022 - avatar
+ 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.
5th Mar 2018, 5:23 AM
RZK 022
RZK 022 - avatar
+ 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.
5th Mar 2018, 4:54 AM
voidneo
+ 1
@noname Thank you so much!😄 It worked! but instead of circular it got elliptical...lol. I need to fix this.😉
5th Mar 2018, 4:56 AM
Шащи Ранжан
Шащи Ранжан - avatar
+ 1
@Atrikant Thanks bro it worked! But what's the reason... those are CSS properties aren't they?
5th Mar 2018, 5:18 AM
Шащи Ранжан
Шащи Ранжан - avatar
+ 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.
5th Mar 2018, 5:28 AM
Шащи Ранжан
Шащи Ранжан - avatar
+ 1
yay! Got it!! Thanks😄😊
5th Mar 2018, 5:39 AM
Шащи Ранжан
Шащи Ранжан - avatar