我想通过触摸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>
答案 0 :(得分: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>
当你将鼠标悬停在它上面时,它将开始每秒调用一次moveLeft(间隔1000毫秒),直到你移开鼠标为止。
代码不是很好,但是它有效,我希望它足够简单,可以解决问题。
答案 1 :(得分: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;
}
另见this example。
答案 2 :(得分:0)
您可以提供填充样式以使矩形可见或绘制边框。其次,您希望将事件附加到按钮以移动在画布上绘制的矩形。可以通过此代码完成,并可以根据您的需要塑造代码。 Demo on JsFiddle using Javascript和Demo on JsFiddle using jQuery
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;
}
);