0

伙计们怎么样了?

最近,在这个网站的帮助下,我学会了如何通过单击按钮在 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>

任何帮助将不胜感激:)

4

1 回答 1

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();
于 2012-06-04T23:10:46.067 回答