在HTML5 Canvas上绘制线条时出现问题

时间:2013-03-14 17:56:48

标签: javascript html5 canvas

<body>
    <canvas id="myCanvas" style="border:1px solid #000000; width: 800px;height:800px">
    </canvas>
</body>

我有一个像这样定义的画布。在准备好视图时,我在画布图形上画了一个箭头。

window.onload = function() {

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "#000000";
    ctx.fillRect(0, 0, 800, 800);
    drawArrow(100, 100, 100, 20, ctx);
};



function drawArrow(x, y, w, h, ctxt) {

    var headWidth = 10;
    ctxt.beginPath();
    ctxt.strokeStyle = "#FF0";
    ctxt.moveTo(x, y + (h / 2));
    ctxt.lineTo(x + w, y + (h / 2));

    //To Draw Arrow Head
    ctxt.moveTo((x + w) - headWidth, y + (h / 2));
    ctxt.lineTo((x + w) - (2 * headWidth), y);
    ctxt.lineTo((x + w), y + (h / 2));
    ctxt.lineTo((x + w) - (2 * headWidth), y + h);
    ctxt.lineTo((x + w) - headWidth, y + (h / 2));

    //To Draw Arrow Tail
    ctxt.moveTo(x + (headWidth), y + (h / 2));
    ctxt.lineTo(x, y);
    ctxt.lineTo(x + (2 * headWidth), y + (h / 6));
    ctxt.lineTo(x + (2 * headWidth), y + (h * (3 / 4)));
    ctxt.lineTo(x, y + h);
    ctxt.lineTo(x + headWidth, y + (h / 2));

    ctxt.lineWidth = 1;
    ctxt.stroke();
} 

即使我将ctxt.lineWidth设置为1,但线宽似乎不是1,而且线条也是拉伸的线条。谁能指出我做错了什么?

3 个答案:

答案 0 :(得分:1)

由于您通过CSS设置宽度和高度。通过CSS更改宽度和高度将更改画布元素的大小,但不会更改像素密度。为此,您必须直接在canvas元素上设置.width.height属性。

onload更改为以下内容,并删除元素上的宽度和高度样式。

<强> Live Demo

window.onload = function() {

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    // canvas width and height set here.
    c.width = 800;
    c.height = 800;

    ctx.fillStyle = "#000000";
    ctx.fillRect(0, 0, 800, 800);
    drawArrow(100, 100, 100, 20, ctx);
};

答案 1 :(得分:1)

<canvas id="myCanvas" width="800" height="800" style="border:1px solid #000000;">
</canvas>

即使您设置了这样的宽度和高度,它也会起作用。

答案 2 :(得分:0)

您必须指定“在像素之间”的坐标。例如,如果您从[0,0][10,0]绘制一条线,则会比从[0.5,0.5][10.5,0.5]绘制更宽的线条。

相关问题