我知道如何画一个正方形,但是我怎样才能让它只在我点击“画正方形”按钮时才绘制呢?另外,我知道要制作一个按钮 ( <p><button onclick="rect();">Rectangle</button></p>
),但是如何将其链接到 javascript?任何帮助都将不胜感激......
HTML5:
<canvas id="canvas" width="500" height="500"></canvas>
JAVASCRIPT:
<script type="text/javascript">
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
rect = {},
drag = false;
function init() {
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('mousemove', mouseMove, false);
}
function mouseDown(e) {
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
drag = true;
}
function mouseUp() {
drag = false;
}
function mouseMove(e) {
if (drag) {
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY ;
ctx.clearRect(0,0,canvas.width,canvas.height);
draw();
}
}
function draw() {
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
init();
</script>