2
<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,而且线条有些拉伸。谁能指出我做错了什么?

4

3 回答 3

1

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

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

现场演示

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);
};
于 2013-03-14T18:02:11.857 回答
1
<canvas id="myCanvas" width="800" height="800" style="border:1px solid #000000;">
</canvas>

即使你像这样设置宽度和高度,它也可以工作。

于 2013-03-15T07:23:56.253 回答
0

您必须指定“像素之间”的坐标。例如,如果你从[0,0]to画一条线,你会得到比从to[10,0]画更宽的线。[0.5,0.5][10.5,0.5]

于 2013-03-14T18:17:14.610 回答