[英]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.