![](/img/trans.png)
[英]Is it possible to set the width and height attributes of a Canvas ID to 90% of the window size?
[英]How to set canvas width / height using parent divs attributes
我一直在尝试在div内设置p5.js画布,并在jekyll帖子中使用divs宽度控制画布的宽度。 在markdown文件中,我正在构造一个div,该div位于帖子的顶部。
<div id="myCanvas"</div>
<script src="/js/p5Sketches/firstP5Sketch.js" type="text/javascript"></script>
在javascript中,我将p5.js画布分配给了div。 我已经尝试获取父级的div clientWidth,但是却得到了一些非常奇怪的输出。
var canvasDiv = document.getElementById('myCanvas');
var width = canvasDiv.clientWidth;
function setup() {
var sketchCanvas = createCanvas(width,450);
sketchCanvas.parent("myCanvas");
}
function draw() {
if (mouseIsPressed){
fill(0);
} else {
fill(255);
}
ellipse(mouseX, mouseY, 40, 40);
if (keyIsPressed == true){
clear();
}
}
function windowResized() {
resizeCanvas(width,450);
}
当我打印出canvasDiv属性时,我得到正确的clientWidth值(844px),但是随后打印出width变量,它是1244px。 在Chrome检查器中,p5画布的宽度最终为width = 100px。
<canvas id="" width="200" height="900" style="width: 100px !important; height: 450px !important;" class=""></canvas>
该值未传递到p5画布上,我不知道为什么。 顺便说一句,我没有使用任何CSS来设置myCanvas或canvas元素的样式。
提前致谢。
您需要在setup()
捕获父元素信息
setup()
的默认宽度和高度为100x100。 如果未在setup()中定义width,则它将被默认值覆盖。 从文档中:
系统变量width和height由传递给此函数的参数设置。 如果未使用createCanvas(),则窗口的默认大小为100x100像素。
https://p5js.org/reference/#/p5/createCanvas
我在这张图中测试并证明了这一点:
以下是正确的代码,应使用以下代码替换setup()函数:
function setup() {
var canvasDiv = document.getElementById('myCanvas');
var width = canvasDiv.offsetWidth;
var sketchCanvas = createCanvas(width,450);
console.log(sketchCanvas);
sketchCanvas.parent("myCanvas");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.