将画布元素添加到DOM

3
我正在尝试使用 appendChild 来调用画布并制作类似 MS Paint 的程序,这里我正在尝试用鼠标进行“绘图”。
我已经尝试将它的高度/宽度更改为只有 500x500,并显示在一个 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(); 
} 
1个回答

3

试着这样使用。

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

document.getElementById('idName') 用于选择一个已存在的元素,它不会创建新元素。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接