Program Tip

HTML5 동적으로 캔버스 만들기

programtip 2020. 12. 1. 19:37
반응형

HTML5 동적으로 캔버스 만들기


안녕하세요, 자바 스크립트를 사용하여 동적으로 캔버스를 만드는 방법에 대한 질문이 있습니다.

다음과 같은 캔버스를 만듭니다.

var canvas = document.createElement('canvas');
canvas.id     = "CursorLayer";
canvas.width  = 1224;
canvas.height = 768;
canvas.style.zIndex   = 8;
canvas.style.position = "absolute";
canvas.style.border   = "1px solid";

그러나 그것을 찾으려고 할 때 null값을 얻습니다 .

cursorLayer = document.getElementById("CursorLayer");

내가 잘못하고 있니? JavaScript를 사용하여 캔버스를 만드는 더 좋은 방법이 있습니까?


문제는 문서 본문에 캔버스 요소를 삽입하지 않는다는 것입니다.

다음을 수행하십시오.

document.body.appendChild(canvas);

예:

var canvas = document.createElement('canvas');

canvas.id = "CursorLayer";
canvas.width = 1224;
canvas.height = 768;
canvas.style.zIndex = 8;
canvas.style.position = "absolute";
canvas.style.border = "1px solid";


var body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);

cursorLayer = document.getElementById("CursorLayer");

console.log(cursorLayer);

// below is optional

var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(255, 0, 0, 0.2)";
ctx.fillRect(100, 100, 200, 200);
ctx.fillStyle = "rgba(0, 255, 0, 0.2)";
ctx.fillRect(150, 150, 200, 200);
ctx.fillStyle = "rgba(0, 0, 255, 0.2)";
ctx.fillRect(200, 50, 200, 200);


Jquery를 통해 :

$('<canvas/>', { id: 'mycanvas', height: 500, width: 200});

http://jsfiddle.net/8DEsJ/736/


DOM이로드되기 전에 호출하기 때문에 발생합니다. 먼저 요소를 만들고 속성을 추가 한 다음 DOM이로드 된 후 호출합니다. 귀하의 경우에는 다음과 같이 보일 것입니다.

var canvas = document.createElement('canvas');
canvas.id     = "CursorLayer";
canvas.width  = 1224;
canvas.height = 768;
canvas.style.zIndex   = 8;
canvas.style.position = "absolute";
canvas.style.border   = "1px solid";
window.onload = function() {
    document.getElementById("CursorLayer");
}

시험

document.body.innerHTML = "<canvas width=500 height=150 id='CursorLayer'>";

var ctx = CursorLayer.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 100, 50, 50);
canvas { border: 1px solid black }

참고 URL : https://stackoverflow.com/questions/10652513/html5-dynamically-create-canvas

반응형