Reputation: 93
I’m trying to use appendChild
here to call up a canvas and make a program like MS Paint and here I'm trying to just 'draw' with my mouse.
I have tried to change the height/width of this to only be 500x500 and appear in-between a div that I need to call too in a div.
I cannot seem to understand why this is not working correctly.
Can someone please help?
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();
}
Upvotes: 3
Views: 1726
Reputation: 1967
Try using like this.
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
document.getElementById('idName')
is used to select an existing element. It doesn't create a new one.
Upvotes: 3