网格线切换HTML5画布

时间:2014-06-11 04:09:36

标签: javascript html5 canvas

我想用开关(ON / OFF)制作网格线x和y但是HTML5画布甚至在ctx.clearRect之后渲染以前绘制的线条,我只想用相同的按钮打开和关闭线条。这是我的小提琴

http://jsfiddle.net/5uayd/1/

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');

  var gridline_x = false,gridline_y = false;

  var grid_x = function(){
      gridline_x = (gridline_x)?false:true;
      GridLines();
  };

  var grid_y = function(){
      gridline_y = (gridline_y)?false:true;
      GridLines();
  };


  var GridLines = function(){

        var ctx = canvas.getContext('2d');
        ctx.clearRect(0,0,canvas.width,canvas.height);


        console.log('Grid  X: '+gridline_x + ' Grid Y: '+gridline_y);
        ctx.save(); 

        if(gridline_y)
        for(var i = 1; i < canvas.width; i += 50) {

            ctx.moveTo( i, 0 );
            ctx.lineTo( i, canvas.height);

        }


        if(gridline_x)
        for(var i = 1; i < canvas.height ; i += 50) {

            ctx.moveTo( 0, i );
            ctx.lineTo( canvas.width, i);
        }

        ctx.strokeStyle = 'hsla(0, 0%, 40%, .5)';
        ctx.stroke();
        ctx.restore();



        //ctx.restore();
    };

第二次点击时删除的行

1 个答案:

答案 0 :(得分:1)

ctx.beginPath()放在ctx.save之后。

beginPath告诉浏览器您已完成之前的路径绘图并开始新绘图。

如果没有beginPath,所有以前的图纸都会重新绘制 - 即使在clearRect

之后