画布不会在它告诉的地方绘制线条

时间:2012-04-01 06:18:15

标签: javascript canvas 2d

我通过画布有这种奇怪的行为,我试图在画布上使用鼠标在自由绘图中绘制路径,画布在X坐标上正确绘制线但是Y开始正确然后随着鼠标移动而滑落,我是什么做错了还是错过了?

<html>
<script>
window.onload = function() {
        var offset = function(obj) {
            var curleft = 0, curtop = 0;
            if (obj.offsetParent) {
                do {
                    curleft += obj.offsetLeft;
                    curtop += obj.offsetTop;
                } while (obj = obj.offsetParent);
                return { x: curleft, y: curtop };
            }
            return undefined;
        }
        var canvas = document.getElementById("d");
        var context = canvas.getContext("2d");
        context.fillStyle = "#fff";
        context.fillRect(0, 0, 300, 300);
        var draw = false;
        var pos = offset(canvas);
        canvas.onmousemove = function(e) {
            if (draw == false) { return; }
            var x = e.pageX - pos.x;
            var y = e.pageY - pos.y;
            console.log(x,y);
            context.lineTo(x, y);
            context.stroke();
        }
        canvas.onmousedown = function(e) {
            draw = true;
            var x = e.pageX - pos.x;
            var y = e.pageY - pos.y;
            context.fillStyle = "#000";
            context.beginPath();
            context.moveTo(x, y);
        }
        canvas.onmouseup = function(e) {
            draw = false;
        }
}
</script>
<style>
#d { border: 1px solid black; width: 300px; height: 300px; }
</style>
<canvas id="d"></canvas>
</html>

由于

1 个答案:

答案 0 :(得分:2)

似乎您需要将宽度/高度属性添加到画布。 我试过&lt; canvas id =“d”width ='300'height ='300'&gt;在小提琴上它起作用。