0

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/

lira153
  • 5
  • 2
  • It might be better if you can provided a working code sample like jsfiddle/codepen in the question. – elpddev Apr 01 '17 at 10:28
  • Alright, added! https://jsfiddle.net/o1rkg1tf/ – lira153 Apr 01 '17 at 11:03
  • I'm not an expert in this, but maybe the js need to be dynamic and accept the size per on the device pixel ratio instead of constant 155, 406.. Like in the answer http://stackoverflow.com/questions/15661339/how-do-i-fix-blurry-text-in-my-html5-canvas#15666143 The resize event you can capture and then redraw the canvas – elpddev Apr 01 '17 at 11:41

1 Answers1

1

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.

Abel
  • 26
  • 2