Dynamically resize canvas within div element
You need to set an explicit height and width on your canvas
tag. In my experience, using CSS to set width/height of a canvas tag results in distortion of the canvas.
Take a look at this question for an example of how to resize a canvas dynamically via a resize handler in JavaScript: HTML5 Canvas 100% Width Height of Viewport?
Hope it helps!
Timothy Trageser
Updated on May 25, 2020Comments
-
Timothy Trageser almost 4 years
I am working on a website and I want to take what I put in between the title tags and make it an element on the page itself. I am also wanting to do some manipulating of the text like adding borders. I am trying to do this with the canvas element, which I have been able to do successfully, but I cannot figure out how to make it scale.
I have found several answers to how to scale if it is taking up the whole screen, but not within div elements. I have just started learning HTML5 and have never done anything like this before any help is appreciated.
javascript code below:
function makeCanvas(){ //1- Get Object var canvas1 = document.getElementById('titlearea'); var ctx1 = canvas1.getContext('2d'); var title = document.getElementById('pagetitle').text; //2- Set parameters ctx1.font = '32pt Arial'; ctx1.fillStyle = 'DeepSkyBlue'; ctx1.strokeStyle = 'Black'; //3- Action ctx1.fillText(title,200,50); ctx1.strokeText(title,200,50); }
HTML snippet below:
<div id="title"> <canvas id="titlearea" width="2000" height="75"></canvas> </div>
CSS snippet below:
#title{ background-color: #E6E6FA; color: #196405; font-size: large; border-bottom:1px solid #000000; padding: 1px; text-align: center; margin:0; width: 100%; height: 75px; }
Any help is appreciated.
-
Timothy Trageser almost 11 yearsAwesome this worked. Now to figure out how to dynamically set the X and Y coordinates based on the canvas size.