【发布时间】:2018-06-25 05:29:21
【问题描述】:
我想要完成的只是在调整大小后在我的画布上重新绘制一些东西。我的问题是,在画布调整大小后,似乎什么都没有出现。我也尝试在调整大小处理程序中放置一些用于绘制矩形的简单代码,我注意到矩形出现在在窗口调整大小期间,然后画布保持空白。下面是我的代码。
var canvass = document.getElementById('zipper-canvas');
var ctx = canvass.getContext('2d');
var repetitions;
var firstRowX = 0; var firstRowY ;
var secondRowX = 5; var secondRowY ;
$(function() {
canvass.width = window.innerWidth;
repetitions = canvass.width / 10;
canvass.height = 30;
ctx = canvass.getContext('2d');
firstRowY = canvass.height / 2 - 3;
secondRowY = canvass.height / 2 + 1;
redraw();
//resize the canvass to fill browser window dynamically
window.addEventListener('resize', resizecanvass, false);
//for some reason i cannot draw on the canvas after it was resized
function resizecanvass() {
canvass.width = window.innerWidth;
repetitions = canvass.width / 10;
canvass.height = 30;
ctx = canvass.getContext('2d');
firstRowY = canvass.height / 2 - 3;
secondRowY = canvass.height / 2 + 1;
/**
* Your drawings need to be inside this function otherwise they will be reset when
* you resize the browser window and the canvass goes will be cleared.
*/
redraw();
}
function redraw() {
canvass = document.getElementById("zipper-canvas");
ctx = canvass.getContext('2d');
ctx.clearRect(0, 0, canvass.width, canvass.height);
console.log(repetitions);
for (var r = 0; r < repetitions; r++) {
ctx.beginPath();
ctx.rect(firstRowX, firstRowY, 5, 5);
ctx.fillStyle = "#edeeef";
ctx.fill();
ctx.closePath();
firstRowX = firstRowX + 10;
}
for (var r2 = 0; r2 < repetitions; r2++) {
ctx.beginPath();
ctx.rect(secondRowX, secondRowY, 5, 5);
ctx.fillStyle = "#a2a3a5";
ctx.fill();
ctx.closePath();
secondRowX = secondRowX + 10;
}
}
});
【问题讨论】:
-
您可能应该取消调整大小事件。它会触发多次。
-
@epascarello 非常感谢,工作就像一个魅力!
-
也许设置一个计时器来防止多个事件。类似于:window.addEventListener('resize', function() { clearTimeout(window.mytimer); window.mytimer = setTimeout(resizecanvass, 1000); }, false);
标签: javascript jquery canvas html5-canvas draw