如何用按钮在画布上绘制正方形

时间:2012-06-03 22:17:08

标签: html5 button draw

我知道如何绘制一个正方形,但是我怎么能这样做它只在我点击“绘制正方形”按钮时绘制?另外,我知道要创建一个按钮(<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> 

1 个答案:

答案 0 :(得分:0)

嗯,您实际上已经通过指定“onclick”属性将您的按钮链接到javascript函数。

现在你只需要在你的js中添加一个rect()函数来绘制一个矩形。