Someone new to coding and first time poster as well. I have been working through a book on canvas and decided to try to make a simple "button" page that will essentially pull up a random "true" or "false".
I set my canvas.width/height to match that of the innerwindow. everything is seamless as i have a resize event except the text, as it stays static. I know i can set it up in a fashion depending on the resolution of the screen, but as mentioned i'm looking for something completely seamless as i resize the window so the text says centered to the "button" and scales with it. I've tried playing with context.scale with no avail. Is it possible?
window.addEventListener('resize', function() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; createPage(); }, false);
var canvas = document.getElementById("draw");
var context= canvas.getContext("2d");
function createCircle(){
context.beginPath(); // is this doing anything? it was working before i used it
context.arc(canvas.width/2,canvas.height/2, canvas.width*(.09),0,360,false );
context.fillStyle="white";
context.fill();
//text
context.fillStyle="black";
context.font="bold 1em sans-serif";
context.textBaseline="middle";
//little messy here trying to center the text
context.fillText("PUSH", canvas.width*(.44), canvas.height/2);
}
function createPage(){
canvas.width = window.innerWidth; canvas.height = window.innerHeight;
//blue
context.fillStyle ="#002db3";
context.fillRect(0,0, canvas.width, canvas.height);
//red
context.fillStyle ="#cc0000";
context.fillRect(0,0, canvas.width, canvas.height*(0.5));
//circle
createCircle();
}
//flash white,setTimeout(yes/no)
function hopeless(){
context.fillStyle="green";
context.fillRect(0,0, canvas.width, canvas.height);
context.fillStyle="black";
context.font="bold 1em sans-serif";
context.textBaseline="middle";
context.fillText("NO ALL IS LOST", canvas.width*(.3), canvas.height/2);
setTimeout(createPage,1000);
}
function hope(){
context.fillStyle="blue";
context.fillRect(0,0, canvas.width, canvas.height);
context.fillStyle="black";
context.font="bold 1em sans-serif";
context.textBaseline="middle";
context.fillText("YES THERE IS HOPE YET", canvas.width*(.2), canvas.height/2);
setTimeout(createPage,1000);
}
function yesOrNo(){
if(Math.random()<.50){
context.fillStyle="white";
context.fillRect(0,0, canvas.width, canvas.height);
setTimeout(hopeless,100);
}else{
context.fillStyle="white";
context.fillRect(0,0, canvas.width, canvas.height);
setTimeout(hope,100);
}
}
createPage();
canvas.addEventListener("click",yesOrNo);
<html >
<head >
<title>Page Title</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body >
<canvas id="draw" ></canvas>
</body>
</html>
thanks everyone!