Reputation: 1817
I read that using multiple canvases instead of drawing everything to one is more efficient so while attempting this I noticed that I was writing code in double. So I got the idea to make a function which would contain all the common variables. Here's the code:
function CanvasElement(id, width, height, parent){
this.id = id;
this.width = width;
this.height = height;
this.parent = parent;
this.canvas = document.createElement('canvas');
document.getElementById(parent).appendChild(this.canvas);
}
However when I use this function like so:
/*Parameters: id, width, height, parent element*/
var canvasBg = new CanvasElement('canvasBg', 640, 480, 'animation');
This is the problem: the final canvas element is smaller than its supposed to be. If one is to make the canvas outside the function "normally" then the final canvas would be 640x480px. However when using the function to create the element the dimensions are considerably smaller.
Any ideas on why this is happening or how to remedy it?
I don't want to rewrite those lines to create multiple canvases. I'd rather have an object I can create and just give the attributes in parameters. I would also like to know if I'm even on the right track on how to implement something like this. Suggestions on how to improve or if necessary apply different methods to achieve the same results are greatly appreciated.
Upvotes: 0
Views: 109
Reputation: 324790
You don't appear to actually be assigning the width or height to the canvas itself, just the CanvasElement
object you have wrapping it.
Try this instead:
function CanvasElement(id,width,height,parent) {
this.canvas = document.createElement('canvas');
this.canvas.id = id;
this.canvas.width = width;
this.canvas.height = height;
document.getElementById(parent).appendChild(this.canvas);
}
Upvotes: 2