728x90
자바스크립트를 이용해서 canvas에 기초적인 사각형을 그리는 예제코드입니다.
[소스코드]
<html>
<body>
<canvas id="space" width="400" height="400"></canvas>
<script>
function keyControl(event) {
canvas = document.getElementById('space');
context = canvas.getContext('2d');
canvasW = canvas.width;
canvasH = canvas.height;
context.fillStyle = "#eeeeee"; // 채우기 색 설정 (회색)
switch (String.fromCharCode(event.keyCode)) { // 누른 키 값에 따라 명령 실행
case 'R': // R키를 눌렀을 때
context.fillStyle = "#FF0000"; // 빨강색으로 채우기값 설정
break;
case 'G': // G키를 눌렀을 때
context.fillStyle = "#00FF00"; // 녹색으로 채우기값 설정
break;
case 'B': // B키를 눌렀을 때
context.fillStyle = "#0000FF"; // 파랑색으로 채우기값 설정
break;
}
context.fillRect(0, 0, canvasW, canvasH); // 색 칠하기
}
window.onload = function() { // html 로드 후에 아래의 코드를 실행
canvas = document.getElementById('space'); // canvas 엘리먼트를 가져오기
context = canvas.getContext('2d'); // 그리기 위한 context를 가져오기
canvasW = canvas.width; // canvas의 너비값을 가져오기
canvasH = canvas.height; // canvas의 높이값을 가져오기
document.onkeydown = keyControl; // key를 눌렀을 때 호출되는 함수 등록
}
</script>
</body>
</html>
getContext함수는 canvas에 할당되어있는 drawing context를 반환합니다.
여기서 drawing context는 그리기 위한 속성과 함수를 가지고 있는 객체를 말합니다.
파라미터로 넘긴 '2d'는 2차원 그리기 context를 가져오기 위함입니다.
다른 방식의 사용은 다음과 같습니다.
- getContext('webgl') : 3차원 렌더링을 위한 컨텍스트를 가져오기
- getContext('webgl2') : WebGL 버전 2에 해당하는 3차원 렌더링 컨텍스트를 가져오기
- getContext('bitmaprenderer') : ImageBitmapRenderingContext에 해당하는 컨텍스트를 가져오기
실행결과는 다음과 같습니다. r, g, b키를 눌러보면 각각 red, green, blue색의 사각형을 다시 그립니다.
728x90
'Web > Javascript' 카테고리의 다른 글
4 Point Sphere (0) | 2022.12.14 |
---|---|
javascript map함수 사용법 (0) | 2022.07.05 |
Electron을 이용한 데스크탑앱 개발 시작하기 (0) | 2022.03.08 |
JavaScript 소수점 반올림 연산 속도 비교(toFixed, Math.round) (0) | 2022.02.15 |