繁体   English   中英

调用函数onclick html5中的按钮

[英]call a function onclick a button in html5

我想通过触摸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>

既然您提到了“触摸”,我想我们需要一个计时器。 画布绘制例程也需要一些固定。 这是我的版本:

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

该操作是将鼠标悬停在鼠标上时,它将每秒每秒调用一次MoveLeft(间隔为1000ms),直到您移开鼠标为止。

代码不是很好,但是它可以工作,我希望它足够简单,可以理解这一点。

下面是移动所有方向和边界检查的示例:

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

另请参见此示例

您可以指定填充样式以使矩形可见或绘制边框。 其次,您想将事件附加到按钮以移动在画布上绘制的矩形。 可以通过此代码完成,也可以根据您的需要模制代码。 使用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;
}
);​

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM