1

所以我今天在玩画布,并创建了一个小脚本,当用户点击屏幕时会放置一个按钮图形。但是,它有一个奇怪的故障:在第一次点击时,线条看起来是深灰色的,在接下来的点击中变成纯黑色。

有人知道为什么会这样吗?

jsfiddle

HTML:

<!DOCTYPE html>
<html>
    <head>
        <link type="text/css" rel="stylesheet" href="paint.css" />
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript" src="paint.js"></script>
    </head>
    <body>
        <div id="container">
            <canvas id="canvas" width="500px" height="500px">Not supported.</canvas>
        </div>
    </body>
</html>

CSS:

html, body {
    border: 0;
    padding: 0;
    margin: 0;

    height: 100%;
    width: 100%;
}

#canvas {
    border: 1px dotted black;
}

Javascript:

var paint = {

    init: function() {  
        var canvas = document.getElementById('canvas'),
            ctx = canvas.getContext('2d');

        $(document).on('click', function(e) {
            var x = e.clientX,
                y = e.clientY;

            paint.draw_button(ctx, x, y, 2, 15);

        });
    },

    draw_button: function(ctx, x, y, scale, rad) {
        scale = scale * 25.5,
        rad = scale - rad;

        ctx.moveTo(x-rad, y-scale);
        ctx.lineTo(x+rad,y-scale);
        ctx.bezierCurveTo(x+rad, y-scale, x+scale,y-scale, x+scale, y-rad);
        ctx.lineTo(x+scale,y+rad);
        ctx.bezierCurveTo(x+scale,y+rad, x+scale, y+scale, x+rad, y+scale);
        ctx.lineTo(x-rad,y+scale);
        ctx.bezierCurveTo(x-rad, y+scale, x-scale, y+scale, x-scale, y+rad);
        ctx.lineTo(x-scale,y-rad);
        ctx.bezierCurveTo(x-scale,y-rad, x-scale, y-scale, x-rad, y-scale);

        ctx.stroke();
    },
};

$(function() {
    paint.init();
});
4

1 回答 1

3

您需要使用该beginPath()方法,否则每次调用stroke()它们时都会累积行。beginPath()将重置路径对象:

draw_button: function(ctx, x, y, scale, rad) {
    scale = scale * 25.5,
    rad = scale - rad;

    ctx.beginPath(); /// here

    ctx.moveTo(x-rad, y-scale);
    ctx.lineTo(x+rad,y-scale);
    ctx.bezierCurveTo(x+rad, y-scale, x+scale,y-scale, x+scale, y-rad);
    ctx.lineTo(x+scale,y+rad);
    ctx.bezierCurveTo(x+scale,y+rad, x+scale, y+scale, x+rad, y+scale);
    ctx.lineTo(x-rad,y+scale);
    ctx.bezierCurveTo(x-rad, y+scale, x-scale, y+scale, x-scale, y+rad);
    ctx.lineTo(x-scale,y-rad);
    ctx.bezierCurveTo(x-scale,y-rad, x-scale, y-scale, x-rad, y-scale);

    ctx.stroke();
}
于 2013-10-12T01:24:17.153 回答