2016-04-05 182 views
2

我試圖在這裏使用appendChild調出一個畫布並製作一個像MS Paint的程序,在這裏我試圖用鼠標'畫'。將畫布元素添加到DOM

我試圖改變這個只有500x500的高度/寬度,並出現在我需要在div中調用的div之間。

我似乎無法理解爲什麼這不能正常工作。

有人可以幫忙嗎?

var canvas = document.getElementById('canvas'); 
document.body.appendChild(canvas); 

var ctx = canvas.getContext('2d'); 
document.body.style.margin = 0; 
canvas.style.position = 'fixed'; 
resize(); 

var pos = { x: 0, y: 0 }; 

canvas.addEventListener('resize', resize); 
canvas.addEventListener('mousemove', draw); 
canvas.addEventListener('mousedown', setPosition); 
canvas.addEventListener('mouseenter', setPosition); 

//what would be the new positions from the "mouse" event. 

function setPosition(e) 
{ 
    pos.x = e.clientX; 
    pos.y = e.clientY; 
} 

function resize() 
{ 
    ctx.canvas.width = window.innerWidth; 
    ctx.canvas.height = window.innerHeight; 
} 

function draw(e) 
{ 
    if (e.buttons! ==1) return; 

    ctx.beginPath(); 
    ctx.lineWidth = 5; 
    ctx.lineCap = 'round'; 
    ctx.strokeStyle = 'red'; 

    ctx.moveTo(pos.x, pos.y); 
    setPosition(e); 
    ctx.lineTo(pos.x, pos.y); 

    ctx.stroke(); 
} 

回答

3

試試像這樣使用。

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

document.getElementById('idName')用於選擇現有的元素。它不會創建一個新的。