Javascript,Canvas和Resizing

时间:2017-04-01 10:06:58

标签: javascript html5 canvas

我希望将一个完成的画布项目调整为可调整大小。我读过的一些网站建议使用CSS来重新设置,但是我也看到人们说永远不会这样做,因为它通过拉伸来模糊文本。但是如果你只是告诉画布在javascript中重新调整大小,那么下面的例子中的filltexts是否需要重做?

var canvas = document.getElementById("example");
var ctx = canvas.getContext('2d');
var cornerRadius = 10;

function drawMe() { 
  ctx.fillStyle = "red";
  ctx.strokeStyle = "red";
  ctx.lineJoin = "round";
  ctx.lineWidth = cornerRadius;
  ctx.strokeRect(5+(cornerRadius/2), 23+(cornerRadius/2), 155-cornerRadius,     406-cornerRadius);
  ctx.fillRect(5+(cornerRadius/2), 23+(cornerRadius/2), 155-cornerRadius,     406-cornerRadius);
  ctx.font = '16pt Arial';
 ctx.fillStyle = 'white';
 ctx.textAlign="start";
 ctx.fillText('Text', 8, 70);
 ctx.fillText('Text', 8, 128);
}

function redraw() {
  ctx.strokeStyle = 'blue';
  ctx.lineWidth = '5';
  ctx.strokeRect(0, 0, window.innerWidth, window.innerHeight);
  drawMe();
}
window.onload = function () {
  redraw();
};

项目示例。
画布在html中设置为1280 x 800。 已修改为包含https://jsfiddle.net/o1rkg1tf/

1 个答案:

答案 0 :(得分:1)

为了使canvas元素可调整大小,您需要处理window resize事件。 之后,您需要将画布宽度和高度设置为窗口大小值。 最后,在canvas元素中使用相对值,主宽度和高度值的百分比。

以下是您的示例的更新: https://jsfiddle.net/abelflopes/o1rkg1tf/5/

var wH = window.innerHeight;
var wW = window.innerWidth;
...
function drawMe() { 
    canvas.height = wH;
    canvas.width = wW;
    ...
}
window.addEventListener("resize", function () {
    wH = window.innerHeight;
    wW = window.innerWidth;
    drawMe();
    redraw();
});

我希望我能够帮助你。

相关问题