生成画布宽度和高度属性,使其大小与用户输入大小的矩形相同
Generating Canvas width and height attributes to be the same size as a rectangle of user inputted size
下面的代码,在启动时,生成一个与画布大小相同的矩形,这是正确的。问题是,当用户单击按钮时,会生成一个新的画布,但矩形没有出现。请帮助。
<!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>
Rectangle Width:
<input type="number" id="width" value="400">
Rectangle Height:
<input type="number" id="height" value="400">
<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.
相关文章:
- 使用javascript搜索具有用户输入的数组
- React Native通过Navigator将用户输入数据传递到选项卡栏IOS中的组件
- 如何使用JavaScript中的用户输入创建序列/序列
- 如何在用户输入时实例化数组
- 如何从客户端的数组中获取用户输入和返回值
- 如何在用户输入 javascript 时更改值
- 如何从多个不同的html页面获得mongodb文档的用户输入
- PayPal按钮是否有一个简单的选项,其中金额基于一些用户输入
- 从表单中获取用户输入执行计算(操作顺序)并输出回该表单
- 我确实有一个表单,如果用户输入了输入,它应该检查否定或空的输入框,并抛出一条警告消息
- 如果用户输入的长度小于最小长度,则显示错误消息
- 随机生成用户输入
- 如果图像标记是用javascript编写的,并且需要用户输入,那么图像不会随页面加载吗
- Javascript:使用用户输入搜索数组
- 根据用户输入的数字生成文本框
- 如何通过获取用户输入和使用按钮来运行JavaScript函数
- 使用用户输入修改链接
- 如何解决取消抖动的用户输入上的竞争条件
- 从用户输入中制作数组动画,如打字机(javascript)
- 如何在视图中保存用户输入内容,并在离开页面时对控制器进行后期调用