使用Canvas HTML绘制“X”字

10

我使用canvas在鼠标点击时绘制“X”单词,但是当我绘制新的“X”单词时,旧的“X”会变成“BOLD”。

http://jsfiddle.net/darklight27/h4JvJ/

你有什么建议吗?谢谢!

3个回答

17

在开始绘制线条之前,调用beginPath()

function drawX(x, y) {
    ctx.beginPath();

    ctx.moveTo(x - 20, y - 20);
    ctx.lineTo(x + 20, y + 20);

    ctx.moveTo(x + 20, y - 20);
    ctx.lineTo(x - 20, y + 20);
    ctx.stroke();
}

更新了 jsFiddle 上的代码:http://jsfiddle.net/h4JvJ/23/


非常感谢,您的指导帮助我节省了很多调试时间 :(( - Dark Light

1

Stefan在上面的回答中画了一个简单的X,只有2条线。如果你想要更粗的X,则可以使用以下函数:

const drawX = (ctx, shape, x, y, size, width) => {
    // Start at the top left corner and draw an X
    ctx.beginPath();
    x -= size;
    y -= size;
    ctx.moveTo(x, y);
    x += width / 2;
    y -= width / 2;
    ctx.lineTo(x, y);
    x += size;
    y += size;
    ctx.lineTo(x, y);
    x += size;
    y -= size;
    ctx.lineTo(x, y);
    x += width / 2;
    y += width / 2;
    ctx.lineTo(x, y);
    x -= size;
    y += size;
    ctx.lineTo(x, y);
    x += size;
    y += size;
    ctx.lineTo(x, y);
    x -= width / 2;
    y += width / 2;
    ctx.lineTo(x, y);
    x -= size;
    y -= size;
    ctx.lineTo(x, y);
    x -= size;
    y += size;
    ctx.lineTo(x, y);
    x -= width / 2;
    y -= width / 2;
    ctx.lineTo(x, y);
    x += size;
    y -= size;
    ctx.lineTo(x, y);
    x -= size;
    y -= size;
    ctx.lineTo(x, y);
    ctx.stroke();
    ctx.closePath();
    ctx.fillStrokeShape(shape);
};

0

可定制的十字架

 var cursor = document.createElement("canvas"),
      ctx = cursor.getContext("2d");

    cursor.width = 36;
    cursor.height = 36;

    // draw some shape for sake of demo
    ctx.strokeStyle = color;

    ctx.lineWidth = 2;

    var x = cursor.width / 2;
    var y = cursor.height / 2;

    // ctx.moveTo(x, y);
    ctx.arc(x, y, 20, 0, 2 * Math.PI);
    ctx.stroke();

    ctx.beginPath();
    ctx.arc(x, y, 30, 0, 2 * Math.PI);

    let lineLength = 22

    ctx.moveTo(x - lineLength / 2, y - lineLength / 2);
    ctx.lineTo(x + lineLength / 2, y + lineLength / 2);
    ctx.stroke();

    ctx.moveTo(x + lineLength / 2, y - lineLength / 2);
    ctx.lineTo(x - lineLength / 2, y + lineLength / 2);
    ctx.stroke();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接