【问题标题】:Appending a Canvas Element to DOM将 Canvas 元素附加到 DOM
【发布时间】:2016-07-24 17:44:14
【问题描述】:

我在这里尝试使用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(); 
} 

【问题讨论】:

    标签: javascript html dom canvas


    【解决方案1】:

    尝试这样使用。

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

    document.getElementById('idName') 用于选择现有元素。它不会创建一个新的。

    【讨论】:

      猜你喜欢
      • 2014-03-10
      • 1970-01-01
      • 2019-05-24
      • 2020-11-10
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-25
      相关资源
      最近更新 更多