모든 방향과 경계 검사 이동 예 :
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 참조.
예. 과? 귀하의 질문은 무엇인가? – KooiInc
그래서 뭘 하려구? 이벤트 핸들러를 부착하는 것은 Q & A 사이트에서 올바르게 가르치기에는 너무 광범위한 주제입니다. 'c.onclick = moveLeft;'답변을 기대할 수는 있지만 응답하지 않습니다. 이 [MDN 튜토리얼] (https://developer.mozilla.org/en/DOM/element.addEventListener)을 읽어보십시오. – kapa
나는 버튼을 만져서 캔버스를 움직이고 싶다 ontouch.rectangle move by 10px –