我在html中有以下代码:
<canvas id="myCanvas" width =800 height=800>
我不想将
width
指定为 800
,而是调用 JavaScript 函数 getWidth()
来获取宽度,例如
<canvas id="myCanvas" width =getWidth() height=800>
正确的语法是什么?因为我正在做的事情不起作用。
您可以这样设置宽度:
function draw() {
var ctx = (a canvas context);
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
//...drawing code...
}
function setWidth(width) {
var canvas = document.getElementById("myCanvas");
canvas.width = width;
}
试试这个:
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>
试试这个:
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 且效果良好。
canvas = new fabric.Canvas("editor", {
selection: true,
uniScaleTransform: true,
preserveObjectStacking: true,
selectionKey: 'ctrlKey',
});
canvas.setHeight(height);
canvas.setWidth(width);
您也可以使用这个脚本,只需更改高度和宽度
<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");