第一章 基础知识
第八节 在Canvas中使用HTML元素
程序清单1-9 使用浮动的DIV元素来实现橡皮筋式选取框
<!DOCTYPE html>
<html>
<head>
<title>Rubber bands with layered elements</title>
<style>
body {
background: rgba(100, 145, 250, 0.3);
}
#canvas {
margin-left: 20px;
margin-right: 0;
margin-bottom: 20px;
border: thin solid #aaaaaa;
cursor: crosshair;
padding: 0;
}
#controls {
margin: 20px 0px 20px 20px;
}
#rubberbandDiv {
position: absolute;
border: 3px solid blue;
cursor: crosshair;
display: none;
}
</style>
</head>
<body>
<div id='controls'>
<input type='button' id='resetButton'value='Reset'/>
</div>
<div id='rubberbandDiv'></div>
<canvas id='canvas' width='800'height='520'>
Canvas not supported
</canvas>
<script src='example.js'></script>
</body>
</html>
这段HTML代码使用了一个包含按钮的DIV元素。如果点击了那个按钮,那么应用程序就会像刚开始启动时那样,将整幅图像都绘制出来。
应用程序又定义了一个DIV元素,用于实现橡皮筋式选取框。这个DIV元素是空的,其CSS的display属性值被设置为none,这样的话,它一开始就是不可见的。当用户拖动鼠标时,应用程序会将这第二个DIV元素设置为可见,如此一来,它的边框就会被显示出来。当你继续拖动鼠标时,应用程序就会持续地修改该DIV的大小,这样就可以制作出图1-17中那样的橡皮筋式选取框效果。
图1-17中应用程序的JavaScript代码列在了程序清单1-10当中。