'drawing circle functions in canvas
i need to draw a circle. it is probably simple and there may be tons of tutorials out there, but i cant find one for my spicific problem. i need to tell it to draw a circle from here:
function startGame() {
//circle needs to be called from here.
//this is how i draw a square
square = new component(40, 40, "blue", 10, 10);
myGameArea.start();
}
and then i need to actually draw it from here:
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
//this is where it draws the stuff
this.update = function() {
var ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
this function is currently programmed to draw squares and not circles. i need to be able to draw and re-draw circles from there. if i create a new funtion, it needs to use the function this.update, and that would overwrite the current one. i need to use it to update game assets, like exampleSquare.update().
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
this calls the
function updateGameArea() {
myGameArea.clear();
}
whitch i left empty for sake of simplicity. if you need my full code you can find it here: https://game.octopuscat.repl.co/ it is kinda messy and has a lot of unimplemented stuff so this is a simplifyed version.
Solution 1:[1]
Add a specifier to the component function. For example you can use a string as the first parameter that defines if you want to draw a circle or square:
function component(type, width, height, color, x, y) {
if(type == "square") {
...
//draw
} else if(type == "circle") {
...
//draw
}
}
And then you can repurpose the parameters if its a circle
... if(type == "circle") {
var radius = width
var diameter = height
//draw
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
