使用 javascript 设置画布大小

我在 html 中有以下代码:

<canvas  id="myCanvas" width =800 height=800>

我希望调用 JavaScript 函数 getWidth()来获得宽度,而不是将 width指定为 800

 <canvas  id="myCanvas" width =getWidth() height=800>

正确的语法是什么? 因为我所做的不起作用。

177011 次浏览
function setWidth(width) {
var canvas = document.getElementById("myCanvas");
canvas.width = width;
}

你可以这样设置宽度:

function draw() {
var ctx = (a canvas context);
ctx.canvas.width  = window.innerWidth;
ctx.canvas.height = window.innerHeight;
//...drawing code...
}

您也可以使用这个脚本,只需更改高度和宽度

<canvas id="Canvas01" width="500" height="400" style="border:2px solid #FF9933; margin-left:10px; margin-top:10px;"></canvas>


<script>
var canvas = document.getElementById("Canvas01");
var ctx = canvas.getContext("2d");

试试这个:

var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
xS = w.innerWidth || e.clientWidth || g.clientWidth,
yS = w.innerHeight|| e.clientHeight|| g.clientHeight;
alert(xS + ' × ' + yS);

Write (”)

为 iframe 工作。

试试这个:

var setCanvasSize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}

要设置画布的宽度和高度,可以使用画布的宽度和高度对象属性来设置宽度和高度。

const canvas = document.getElementById('canvas')
canvas.width = 350     // 350px
canvas.height = 200    // 200px
#canvas {
background-color:blue
}
<canvas id="canvas"></canvas>