简体   繁体   English

网格线开关HMTL5帆布

[英]Grid lines Switch HMTL5 Canvas

I want to make grid line x and y with switch(ON/OFF) but the HTML5 canvas is rendering previous drawn lines even after ctx.clearRect, I just want to on and off the lines with the same buttons. 我想使用switch(ON / OFF)来制作网格线x和y,但是HTML5画布甚至在ctx.clearRect之后仍渲染先前绘制的线条,我只想使用相同的按钮来打开和关闭线条。 Here is my fiddle 这是我的小提琴

http://jsfiddle.net/5uayd/1/ 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();
    };

the lines don't remove on second click 第二次单击时线条不会移除

Put ctx.beginPath() just after your ctx.save . ctx.beginPath()只是你以后ctx.save

beginPath tells the browser you're done with previous path drawings and are beginning a new drawing. beginPath告诉浏览器您已经完成了先前的路径图并正在开始新的图。

Without beginPath , all the previous drawings will be redrawn--even after clearRect 没有beginPath ,即使在clearRect之后,所有先前的图形也将被重绘

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM