【问题标题】:HTML 5 Canvas drawing app not drawingHTML 5 Canvas 绘图应用程序不绘图
【发布时间】:2013-03-14 14:57:33
【问题描述】:

我有一个简单的 html5 画布绘图应用程序的以下代码(代码来自 here)。但是,我无法让画布在鼠标按下时进行绘制。有任何想法吗?

在 Firefox 中尝试过,而不是 IE。

任何帮助表示赞赏。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>   
<script type="text/javascript">  
    var canvas = document.querySelector('#paint');
    var ctx = canvas.getContext('2d');  
    var sketch = document.querySelector('#sketch');
    var sketch_style = getComputedStyle(sketch);
    canvas.width = parseInt(sketch_style.getPropertyValue('width'));
    canvas.height = parseInt(sketch_style.getPropertyValue('height')); 
    var mouse = {x: 0, y: 0};
    var last_mouse = {x: 0, y: 0};  

    /* Mouse Capturing Work */
    canvas.addEventListener('mousemove', function(e) {
        last_mouse.x = mouse.x;
        last_mouse.y = mouse.y;

        mouse.x = e.pageX - this.offsetLeft;
        mouse.y = e.pageY - this.offsetTop;
    }, false);


    /* Drawing on Paint App */
    ctx.lineWidth = 5;
    ctx.lineJoin = 'round';
    ctx.lineCap = 'round';
    ctx.strokeStyle = 'blue';       
    canvas.addEventListener('mousedown', function(e) {
        canvas.addEventListener('mousemove', onPaint, false);
    }, false);

    canvas.addEventListener('mouseup', function() {
        canvas.removeEventListener('mousemove', onPaint, false);
    }, false);

    var onPaint = function() {
        ctx.beginPath();
        ctx.moveTo(last_mouse.x, last_mouse.y);
        ctx.lineTo(mouse.x, mouse.y);
        ctx.closePath();
        ctx.stroke();
    };

    </script>
<style type="text/css">
html, body {
    width: 100%;
    height: 100%;
}
#sketch {
    border: 10px solid gray;
    height: 100%;
}
</style>
</head>
<body>
<div id="sketch">
  <canvas id="paint"></canvas>
</div>
</body>
</html>

【问题讨论】:

    标签: canvas svg jquery-svg


    【解决方案1】:

    问题是您试图访问尚未加载的标签 (var canvas = document.querySelector('#paint');)。

    将整个 JavaScript 标记放在 &lt;/canvas&gt; 标记之后。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多