简体   繁体   中英

Javascript, Canvas, and Resizing

I'm looking to make a finished canvas project resizeable. Some websites I've read recommend using CSS to restyle, however I've also seen people say never to do that because it blurs text by stretching things. But if you simply tell the canvas to resize in javascript won't filltexts such as in the example below need to be redone?

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();
};

Example of project.
Canvas is set in html to 1280 x 800. edited to include https://jsfiddle.net/o1rkg1tf/

In order to get a canvas element resizable, you need to handle the window resize event. After that you need to set the canvas width and height to the window size values. And finally, in your canvas element use relative values, percentages of the main width and height values.

Here's an update of your example: 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();
});

I hope i was clear enough to help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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