简体   繁体   English

单击链接时画布变量未更新

[英]Canvas variable not updating when link is clicked

See link: http://jndgn.com/colortheory/bezold.html 参见链接: http : //jndgn.com/colortheory/bezold.html

When clicking the 'Bigger Stripes' link in the nav I'm attempting to simply update the number of colored stripes in the canvas below it. 当单击导航中的“较大条纹”链接时,我试图仅更新其下方画布中彩色条纹的数量。 The variable 'stripeNum' is set at 100 and when clicked should change to 20 via: 变量“ stripeNum”设置为100,单击时应通过以下方式更改为20:

$(function(){
  $("#stripes").on("click",function(e){
    e.preventDefault();

    if(stripeNum == 100) {
        stripeNum = 20;
    } else {
        stripeNum = 100;
    }       
  });
})

...but when clicked, no action occurs. ...但是单击时不会执行任何操作。 Do I somehow need to get the canvas to update itself? 我是否需要以某种方式使画布进行自我更新? A bit of an HTML5 rookie here. 这里有一些HTML5新手。 Thanks in advance for any thoughts. 预先感谢您的任何想法。

JSFiddle attached for easier code transparency. 附加了JSFiddle,以提高代码透明度。

You need to re-draw the canvas, as well as clearing it when you do this. 您需要重新绘制画布,并在执行此操作时将其清除。 You could simply make this adjustment and you'd be good: 您可以简单地进行此调整就可以了:

First, wrap the canvas drawing you have in a function: 首先,将您拥有的画布图形包装在一个函数中:

var contextFill = function() {
  context.clearRect(0, 0, canvas.width, canvas.height); // Clear on draw
  for (var i = 0; i < stripeNum + 1; i++) {
    context.beginPath();
    context.rect(0, i * canvas.height / stripeNum, canvas.width, canvas.height / (2 * stripeNum));
    context.fillStyle = randomColor;
    context.fill();
   }
}

Then, call contextFill() on document ready. 然后,在准备就绪的文档上调用contextFill() The only addition I made to the above is context.clearRect , to clear the canvas. 我对上面所做的唯一添加是context.clearRect ,以清除画布。

Finally, also call it when your bigger stripes is called, eg: 最后,在调用较大的条纹时也调用它,例如:

...
if (stripeNum == 100) {
     stripeNum = 20;
} else {
     stripeNum = 100;
}    
contextFill();

If you want to update canvas on window resize, you can watch the resize event on the window. 如果要在窗口调整大小时更新画布,可以在窗口上观看resize事件。 The downside is it can occur many times depending on how the user is resizing. 不利的一面是,根据用户调整大小的方式,它可能会发生很多次。 You can use a library like lodash to ensure that the function only is called every N milliseconds. 您可以使用lodash之类的库来确保仅每N毫秒调用一次该函数。 For example: 例如:

window.addEventListener('resize', _.debounce(function() {
     contextFill();
}, 500));

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

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