简体   繁体   English

画布尺寸已关闭

[英]Canvas dimensions are off

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. 这就是问题:最终的canvas元素比它应该的要小。 If one is to make the canvas outside the function "normally" then the final canvas would be 640x480px. 如果要使画布在“正常”功能之外,则最终画布将为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. 非常感谢关于如何改进或必要时应用不同方法以获得相同结果的建议。

You don't appear to actually be assigning the width or height to the canvas itself, just the CanvasElement object you have wrapping it. 您似乎并没有实际为画布本身分配宽度或高度,只是将包装它的CanvasElement对象分配给它。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM