怎么回事?
最近,在这个网站的帮助下,我学会了如何在点击按钮的情况下在HTML5画布上绘制一个矩形......这不是问题:)这是问题...不幸的是,当我试图在我的iPhone上使用它时,它根本无法工作......为什么:(?
这是我的代码:
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 ;
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>
任何帮助都将非常感谢:)
答案 0 :(得分:0)
首先你的代码出错了 你明星这个
rect() {
并仅在脚本结束时关闭它
在触摸设备上,您需要使用触摸*事件我认为
类似这样的事情
var canvas = document.getElementById('canvasSignature'), ctx = canvas.getContext('2d'), rect = {}, drag = false;
function init() {
canvas.addEventListener("touchstart", touchHandler, false);
canvas.addEventListener("touchmove", touchHandler, false);
canvas.addEventListener("touchend", touchHandler, false);
}
function touchHandler(event) {
if (event.targetTouches.length == 1) { //one finger touche
var touch = event.targetTouches[0];
if (event.type == "touchstart") {
rect.startX = touch.pageX;
rect.startY = touch.pageY;
drag = true;
} else if (event.type == "touchmove") {
if (drag) {
rect.w = touch.pageX - rect.startX;
rect.h = touch.pageY - rect.startY ;
draw();
}
} else if (event.type == "touchend" || event.type == "touchcancel") {
drag = false;
}
}
}
function draw() {
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
init();