2

HTML5でボタンタッチで関数を呼び出したい。長方形を描いたキャンバスを持っています。

これが私のコードです:

<body>
<canvas id="canvas" width="200" height="300"></canvas>
<button id="as" type="button">Left</button></body>
<script>
    var inc=10;
    var c=document.getElementById("canvas");
    ctx = c.getContext("2d");
    ctx.fillRect(x,0,150,75);
    function moveLeft(){ x+=inc }
</script>
4

3 に答える 3

2

ここでは、すべての方向と境界チェックを移動する例を示します。

HTML:

<canvas id="canvas"></canvas><br>
<button type="button" onclick="moveRect(0, -10);">move up</button><br>
<button type="button" onclick="moveRect(-10, 0);">move left</button>
<button type="button" onclick="moveRect(+10, 0);">move right</button><br>
<button type="button" onclick="moveRect(0, +10);">move down</button>

JS:

var c = null, ctx = null, x = 0, y = 0;
var width = 150, height = 75;

function moveRect(x2, y2) {
    ctx.clearRect(x, y, width, height);
    x += x2;
    if (x < 0) x = 0;
    else if (x > c.width - width) x = c.width - width;
    y += y2;
    if (y < 0) y = 0;
    else if (y > c.height - height) y = c.height - height;
    ctx.fillRect(x, y, width, height);
}

window.onload = function() {
    c = document.getElementById("canvas");
    ctx = c.getContext("2d");
    x = 0;
    moveRect(0, 0);
}

CSS:

#canvas {
    width: 200;
    height: 300px;
    border: 1px solid red;
}

この例も参照してください。

于 2012-05-17T11:06:23.847 に答える
2

「タッチ」とおっしゃっていたので、タイマーが必要だと思います。キャンバス描画ルーチンも修正が必要です。これが私のバージョンです:

<html><body>
<canvas id="canvas" width="200" height="300" style='border:1px solid black'></canvas>
<button id="as" type="button" onmouseover='startMove()' onmouseout='stopMove()'>Left</button></body>
<script>
    var c=document.getElementById("canvas");
    var ctx = c.getContext("2d");
    var inc = 10;
    var timer = 0;
    var x = 100;
    function moveLeft(){ if ( x > 0 ) x-=inc; drawCtx(); }
    function drawCtx(){ ctx.clearRect(0,0,200,300); ctx.fillStyle='black'; ctx.fillRect(x,0,50,75); }
    function startMove(){ stopMove(); timer = setInterval(moveLeft, 1000);  }
    function stopMove(){ clearInterval(timer); }
    drawCtx();
</script>

これが何をするかというと、マウスオーバーすると、マウスを離すまで、1 秒に 1 回 (1000 ミリ秒間隔) moveLeft の呼び出しが開始されます。

コードは良くありませんが、機能します。要点を理解するのに十分単純であることを願っています。

于 2012-05-17T10:53:20.577 に答える
0

塗りつぶしスタイルを指定して、長方形を表示したり、境界線を描画したりできます。次に、キャンバスに描画された長方形を移動するために、ボタンにイベントを添付します。これはこのコードで実行でき、必要に応じてコードを成形できます。Javascriptを使用した JsFiddle のデモと jQuery を使用した JsFiddleのデモ

x =200;
$('#as').click(function()
{    
    var inc=10;
    var c=document.getElementById("canvas");
    //c.style.backgroundColor = "#ff0000";
    ctx = c.getContext("2d");    


    ctx.fillStyle="#ff0000";    
    ctx.fillRect(x+5,0,15,75);


    ctx.fillStyle="#ffffff";    
    ctx.fillRect(x,0,15,75);
    x-=5;
}
);​
于 2012-05-17T10:50:58.640 に答える