Mohammed Hammed Mohammed Hammed - 1 month ago 15
Javascript Question

Little issue with canvas

I'm trying to run this code, where the constructor is the ball function, and the

ball.prototype.draw
is the prototype which should include the code in ball.

Can't seem to display the drawing of the ball.

var canvas = document.getElementById('ok');
var d = canvas.getContext('2d');
function Ball() {
ok = 100;
okk = 100;
};

var circle = function(x, y, radius, fillCircle){
d.beginPath();
d.arc(x, y, radius, 0, Math.PI * 2, false);
if(fillCircle){
d.fill();
} else{
d.stroke(); } };

Ball.prototype.draw = function() {
d.lineWidth = 2;
d.strokeStyle = "black";
d.fillStyle = "red";
circle(ok, okk, 30, true); };

Ball.prototype.draw();

Answer

When using the prototypes in JS, you still would need to instantiate a new instance of the object you're modeling.

So your code is fine, except the last line; instead you want to create a new ball and then call the member function draw on it, like so:

//Ball.prototype.draw();
var ball = new Ball();
ball.draw();