怎么样了?
最近,在这个网站的帮助下,我学会了如何通过单击按钮在 HTML5 画布上绘制一个矩形......这不是问题:) 这是问题......不幸的是,每次我单击画布以创建一个新矩形,旧矩形消失(或立即擦除)。当我尝试在我的 iPod 上使用它时,它也完全不起作用......为什么:(?
这是我的代码:
JAVASCRIPT:
// "Rectangle" Button
function rect()
{
var canvas = document.getElementById('canvasSignature'),
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();
}
HTML5:
<div id="canvasDiv">
<canvas id="canvasSignature" width="580px" height="788px" style="border:2px solid #000; background: #FFF;"></canvas>
</div>
<div id="rect">
<p><button onclick="rect();">Rectangle</button></p>
</div>
任何帮助将不胜感激:)