【发布时间】:2014-07-11 22:30:06
【问题描述】:
我希望能够使用来自用户的输入即时创建图表和绘图。
如果我有 2 个用于宽度和高度的文本框,我希望能够根据用户输入的值绘制一个矩形,如果他们更改了输入字段中的值,我希望绘图也随之改变。
canvas 能做到这一点吗?它需要与 javascript 一起工作吗?
谢谢
【问题讨论】:
标签: html html5-canvas
我希望能够使用来自用户的输入即时创建图表和绘图。
如果我有 2 个用于宽度和高度的文本框,我希望能够根据用户输入的值绘制一个矩形,如果他们更改了输入字段中的值,我希望绘图也随之改变。
canvas 能做到这一点吗?它需要与 javascript 一起工作吗?
谢谢
【问题讨论】:
标签: html html5-canvas
是的,您可以监听文本输入并发出适当的画布绘图命令。
所有画布命令都必须用 javascript 发出...所以是的,javascript 是必需的。
这里是带注释的代码和一个演示:http://jsfiddle.net/m1erickson/f6E6Y/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
// get a reference to the canvas and context
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// vars for current width and height of a canvas rectangle
var width=50;
var height=35;
// references to the input-text elements
// used to let user change the rect width & height
var $width=document.getElementById('width');
var $height=document.getElementById('height')
// set the initial input-text values to the width/height vars
$width.value=width;
$height.value=height;
// call the draw command
draw();
// listen for keyup events on width & height input-text elements
// Get the current values from input-text & set the width/height vars
// call draw to redraw the rect with the current width/height values
$width.addEventListener("keyup", function(){
width=this.value;
draw();
}, false);
$height.addEventListener("keyup", function(){
height=this.value;
draw();
}, false);
// draw() clears the canvas and redraws the rect
// based on user input
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillRect(40,40,width,height);
}
}); // end $(function(){});
</script>
</head>
<body>
Width:<input type="text" id="width"><br>
height:<input type="text" id="height"><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
【讨论】: