【问题标题】:Offset when drawing on canvas在画布上绘图时偏移
【发布时间】:2012-01-01 15:01:59
【问题描述】:

有一个简单的绘图应用程序。问题在于坐标(redraw 函数):它们必须是鼠标,但接近 2x 鼠标。代码有什么问题?

<html>
<head>
    <style type="text/css" media="screen">
body{
    background-color: green;
}

#workspace{
    width: 700px;
    height:420px;
    margin: 40px auto 20px auto;
    border: black dashed 1px;
}

#canvas{
    background: white;
    width: 100%;
    height: 100%;
}
    </style>
<script type="text/javascript" src="jquery-1.7.1.js"></script> 
<script type="text/javascript">
$(document).ready(
    function() {
        var context = document.getElementById('canvas').getContext("2d");
        var clickX = new Array();
        var clickY = new Array();
        var clickDrag = new Array();
        var paint;

        $('#canvas').mousedown(function(e){
            var mouseX = e.pageX - this.offsetLeft;
            var mouseY = e.pageY - this.offsetTop;
            paint = true;
            addClick(mouseX,mouseY, false);
            redraw();
        });

        $('#canvas').mousemove(function(e){
            if(paint){
                addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
                redraw();
            }
        });

        $('#canvas').mouseup(function(e){
            paint = false;
        });

        $('#canvas').mouseleave(function(e){
            paint = false;
        });

        function addClick(x, y, dragging)
        {
            clickX.push(x);
            clickY.push(y);
            clickDrag.push(dragging);
        }

        function redraw(){
            canvas.width = canvas.width; // Clears the canvas

            context.strokeStyle = "#df4b26";
            context.lineJoin = "round";
            context.lineWidth = 5;

            for(var i=1; i < clickX.length; i++)
            {
                context.beginPath();
                if(clickDrag[i] && i){
                    context.moveTo(clickX[i-1], clickY[i-1]);
                }else{
                    context.moveTo(clickX[i], clickY[i]);
                }
                context.lineTo(clickX[i], clickY[i]);
                context.closePath();
                context.stroke();
            }

            console.log(clickX[clickX.length-1]+" "+clickY[clickX.length-1]);
        }
    });
</script>
</head>
<body>
<div id="workspace">
<canvas id="canvas"/>
</div>
</body>
</html>

【问题讨论】:

    标签: javascript jquery mouse draw html5-canvas


    【解决方案1】:

    您不应通过 CSS 设置画布的宽度/高度。它使画布拉伸而不是使分辨率更高。这意味着虽然坐标是正确的,但它们在视觉上会在其他地方结束。

    例如,100 的 x 坐标将在视觉上被拉伸为 200 的 x 坐标(或其他东西;至少它会比 100 大,因为它已被拉伸)。

    改为使用:

    <canvas id="canvas" width="700" height="420" />
    

    并删除 CSS 中的 width: 100%

    http://jsfiddle.net/euXJC/1/

    【讨论】:

    • 删除css 中的width 是我的关键
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    相关资源
    最近更新 更多