我是javascript的新手,我不知道如何获取收集的输入值(宽度和高度),然后需要创建一个名为updateForm的方法,该方法采用width和height参数。函数体可以在输入窗体上设置宽度和高度字段,并调用方法在画布上绘制该矩形。
JS小提琴 - https://jsfiddle.net/rtomino/hbgmd4sg/2/
<form id="areaform">
<label for="wid">Width:</label>
<input id="wid" type="number">
<label for="hgt">Height:</label>
<input id="hgt" type="number">
<button onclick="draw()" type="button">Draw Rectangle</button>
</form>
<br>
<div id="drawRectangle">
<canvas id="rectCanvas" width=500 height=500></canvas>
</div>
JS
var canvas,
context,
widthValue = document.getElementById('wid'),
heightValue = document.getElementById('hgt');
canvas = document.getElementById("rectCanvas");
context = canvas.getContext("2d");
function updateForm(width, height) {
'use strict';
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.rect(0, 0, width, height);
context.fillStyle = "#EA7B00";
context.fill();
}
答案 0 :(得分:1)
我在此 CodePen Demo 中使用了updateForm
功能,以及下面的代码段。
画布宽度/高度设置为100%,为您提供了使矩形非常大的空间,但您可以在JavaScript中设置任何您想要的画布尺寸。
function updateForm(width, height) {
"use strict";
//Position parameters used for drawing the rectangle
var x = 50;
var y = 50;
var canvas = document.createElement("canvas"); //Create a canvas element
//Set canvas width/height
canvas.style.width = "100%";
canvas.style.height = "100%";
// Set canvas drawing area width/height
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//Position canvas
canvas.style.position = "absolute";
canvas.style.left = 0;
canvas.style.top = 0;
canvas.style.zIndex = 100000;
canvas.style.pointerEvents = "none"; //Make sure you can click 'through' the canvas
document.body.appendChild(canvas); //Append canvas to body element
var context = canvas.getContext("2d");
//Draw rectangle
context.rect(x, y, width, height);
context.fillStyle = "blue";
context.fill();
}
function draw() {
var width = document.getElementById("wid").value;
var height = document.getElementById("hgt").value;
updateForm(width, height);
}
<form id="areaform">
<label for="wid">Width:</label>
<input id="wid" type="number">
<label for="hgt">Height:</label>
<input id="hgt" type="number">
<button onclick="draw()" type="button">Draw Rectangle</button>
</form>
此解决方案改编自this answer。