[英]how to set canvas size on inputted height and width in my image editor?
[英]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分开的属性,该ID称为“宽度”,并且更改确实会更改画布的尺寸。 如果您不想通过jquery获取高度和宽度,则可以使用
document.getElementById("myCanvas").height
document.getElementById("myCanvas").width
尝试在您的代码中分别更改height和width变量。
在用jQuery( $("#btn").click(function(){...});
)定义的侦听器之前,将执行onclick
属性中的javascript代码。 因此,当您单击“提交”按钮时,在更改canvas元素的尺寸之前将调用rect
函数,因此将清空画布内容。 画布大小更改后,您需要调用rect
: Plunker 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.