HTML <canvas> width 属性

htmlweb developmentfront end technology更新于 2025/9/18 22:36:17

<canvas> 元素的 width 属性用于设置画布的宽度(以像素为单位)。语法如下:−

<canvas width="pixels_val">

以上,pixels_val 是以像素为单位设置的宽度。现在让我们看一个实现 <canvas> 元素 width 属性的示例 −

示例

<!DOCTYPE html>
<html>
<body>
<canvas id="newCanvas" width="400" height="200" style="border:3px dashed yellow">
HTML5 canvas tag isn't supported by your browser.
</canvas>
<script>
   var c = document.getElementById("newCanvas");
   var context = c.getContext("2d");
   context.fillStyle = "#FF5655";
   context.fillRect(100, 50, 60, 100);
</script>
</body>
</html>

输出

在上面的例子中,我们创建了一个画布并使用了 JavaScript −

<script>
   var c = document.getElementById("newCanvas");
   var context = c.getContext("2d");
   context.fillStyle = "#FF5655";
   context.fillRect(100, 50, 60, 100);
</script>

在此之前,我们已设置画布 ID、宽度和高度 −

<canvas id="newCanvas" width="400" height="200" style="border:3px dashed yellow">
   HTML5 canvas tag isn't supported by your browser.
</canvas>

相关文章


有用资源