call a function onclick a button in html5

43,393

Solution 1

Since you mentioned 'touch', I guess we'll need a timer. The canvas draw routine also need some fixing. Here is my version:

<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>

What this do is when you mouse over it will start calling moveLeft once per second (1000ms interval) until you move away the mouse.

Code is not nice, but it works and I hope it is simple enough to get the point across.

Solution 2

Here an example moving all directions and border checking:

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;
}

Also see this example.

Share:
43,393
Laxmi Kant
Author by

Laxmi Kant

Updated on May 07, 2020

Comments

  • Laxmi Kant
    Laxmi Kant about 4 years

    I want to call a function by touching a button in HTML5. I haveange in a canvas drawn a rect.

    Here is my code:

    <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>