生成画布宽度和高度属性,使其大小与用户输入大小的矩形相同

Generating Canvas width and height attributes to be the same size as a rectangle of user inputted size

本文关键字:用户 输入 布宽度 高度 属性      更新时间:2023-09-26

下面的代码,在启动时,生成一个与画布大小相同的矩形,这是正确的。问题是,当用户单击按钮时,会生成一个新的画布,但矩形没有出现。请帮助。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script>
$(document).ready(function(){ <!-- function to change the <canvas> attributes of "width" and "height" to the same size as the rectangle -->
   $("#btn").click(function(){
   $("#myCanvas").attr("height", $("#height").val());
   $("#myCanvas").attr("width", $("#width").val());
  });
});
</script>
</head>
<body>
  &nbsp;Rectangle Width:
  <input type="number" id="width" value="400">
  &nbsp;Rectangle Height:
  <input type="number" id="height" value="400">
  &nbsp;    
  <br>
  <canvas id="myCanvas" width=400 height=400 style="border:0px solid #d3d3d3;"> 
  Your browser does not support the HTML5 canvas tag.</canvas>
<script>
rect();
function rect(){
  width = document.getElementById("width").value;
  height = document.getElementById("height").value;
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  ctx.strokeStyle = "#FF0000";
  ctx.strokeRect(0,0, width, height);
}
</script>
<button id="btn" onclick = "rect()">Submit to draw a rectangle the same size as the canvas</button>     
</body>
</html>

删除$(document).ready(function(){函数,然后更改rect()函数,如下所示:-

 function rect(){ 
   width = document.getElementById("width").value;
   height = document.getElementById("height").value;
   var c = document.getElementById("myCanvas");
   var ctx = c.getContext("2d");
   ctx.canvas.height = height;//add this 
   ctx.canvas.width = width;// and this
   ctx.strokeStyle = "#FF0000";
   ctx.strokeRect(0,0, width, height);    

}

演示

当你调用rect函数时,你得到了width的id,我不确定那实际上会解析成什么。

width = document.getElementById("width").value;

,但在按钮点击,你正在创建一个独立于id的属性称为"宽度",这改变确实改变了画布的尺寸。如果你不想用jquery获取高度和宽度,你可以使用

document.getElementById("myCanvas").height
document.getElementById("myCanvas").width

试着在你的代码中分别改变高度和宽度变量

onclick属性中的javascript代码在使用jQuery ($("#btn").click(function(){...});)定义的侦听器之前执行。因此,当单击提交按钮时,在更改画布元素的尺寸之前调用rect函数,因此清空画布内容。你需要在画布大小改变后调用rect: Plunker.