简体   繁体   English

如何在javascript中确定HTML5画布的大小和位置

[英]how to size and position a html5 canvas in javascript

i am using javascript to dynamically create a canvas and display it on a webpage but the size of the canvas and the position of the canvas both vary based on the size of the device that is viewing the webpage whether it be mobile, or desktop. 我正在使用JavaScript动态创建画布并将其显示在网页上,但是画布的大小和画布的位置均根据查看网页的设备的大小而有所不同,无论该设备是移动设备还是台式机。 I would do this in css, however the css does not work fullyfor html5 canvases as far as i know. 我会在CSS中执行此操作,但是据我所知,CSS无法完全用于html5画布。 I would use this: 我会用这个:

#myCanvas{
  height: 50%;
  width: 50%;
  position: relative;
  top: 10%;
  left: 10%;
}

however the height and width values for the canvas only take pixel values and the only solution i could think for that is to get the size of the parent element and then get a portion of that to depict what size i wanted the canvas to be. 但是,画布的高度和宽度值仅采用像素值,我唯一能想到的解决方案是获取父元素的大小,然后获取其中的一部分来描述我希望画布的大小。 however if that doesnt work i dont know. 但是,如果那不起作用,我不知道。 As far as the positioning goes i have no idea what i am supposed to do. 就定位而言,我不知道我应该做什么。 And like i said i am creating the canvas dynamically so the code looks like this: 就像我说的那样,我是动态创建画布的,因此代码如下所示:

var c = document.createElement("canvas");
c.height = (whatever value);
c.width = (whatever value);
c.style.position = "relative";
c.style.top = (whatever value);
c.style.left = (whatever value);
var ctx = c.getContext('2d');
parentElement.appendChild('c');

if anyone can give me a solution to my problem it would be very helpful thank you =) 如果有人可以给我解决我的问题的方法,那将非常有帮助,谢谢=)

Enclose the canvas in a container div, set the dimension of this div to be proportional instead of fixed. 将画布封闭在容器div中,将该div的尺寸设置为成比例而不是固定。 Then, use the JQuery "resize" function to set the dimension of the canvas to be the width and height of the container div. 然后,使用JQuery的“调整大小”功能将画布的尺寸设置为容器div的宽度和高度。

$(window).resize(function() {
   $('#canvas').attr('width', $('#parent').width());
   $('#canvas').attr('height', $('#parent').height());
});

Read this article for more info: http://ameijer.nl/2011/08/resizable-html5-canvas/ 阅读本文以了解更多信息: http : //ameijer.nl/2011/08/resizable-html5-canvas/

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

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