Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 向DOM追加画布元素_Javascript_Html_Dom_Canvas - Fatal编程技术网

Javascript 向DOM追加画布元素

Javascript 向DOM追加画布元素,javascript,html,dom,canvas,Javascript,Html,Dom,Canvas,我试图在这里使用appendChild调用画布并制作一个类似MS-Paint的程序,在这里我试图用鼠标“绘制” 我已经尝试将其高度/宽度更改为仅为500x500,并出现在我需要在div中调用的div之间 我似乎无法理解为什么这不能正常工作 有人能帮忙吗 var canvas = document.getElementById('canvas'); document.body.appendChild(canvas); var ctx = canvas.getContext('2d'); doc

我试图在这里使用
appendChild
调用画布并制作一个类似MS-Paint的程序,在这里我试图用鼠标“绘制”

我已经尝试将其高度/宽度更改为仅为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(); 
} 
试着像这样使用

var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
document.getElementById('idName')
用于选择现有元素。它不会创建一个新的