HTML5 Canvas resizes only html - javascript

I am currently working on a project involving the canvas element and have come across a problem when I resize the canvas. I'm trying to draw an image at the center of the canvas by dividing the width and height by 2, but whenever I resize the canvas, it only changes the HTML, so when I go to redraw the image, it still draws at half the width and height of the old canvas. I'm not sure if this is a DOM issue or what, but would appreciate any help. I have tested in Safari, FF, and Chrome
Edit: Code
<body>
<div id="holder">
<div id="dropdown">
<div id="ddcontents" style="display: none;">
<button onclick="fade()">Options</button>
<button onclick="getSize()">Canvas Size</button>
<button onclick="redraw()" disabled="true">Redraw</button>
</div>
</div>
<canvas id="c" height="480" width="640">Your browser does not support HTML5.</canvas>
<div id="options" style="display: none">
<div id="optcontent" style="display: none">
<center><h1>Options</h1></center>
<div id="sound">
<div>Volume:
<form oninput="volumenumber.value = parseInt(volume.value)">
<input type="range" name="volume" min="0" max="100" value="80" disabled="true">
<input type="hidden" name="hello" value="%">
<output name="volumenumber" for="volume">80</output>
</form>
Resolution:
<select id="resolution">
<option value="480p">480x640</option>
<option value="720p">720x1280</option>
</select>
</div>
</div>
<div id="closeoptions">
<button onclick="apply()">Apply</button>
</div>
</div>
</div>
</div>
<script src="options.js"></script>
</body>
</html>
And for the JS:
var c = document.getElementById('c');
var ctx=c.getContext("2d");
var img=new Image();
var w = this.c.clientWidth; // stores the width for later use
var h = this.c.clientHeight;
this.c.width = w;
this.c.height = h;
var cwidth = c.width;
var cheight = c.height;
img.onload = function(){
ctx.drawImage(img,w/2 - 14,h/2 - 19);
};
img.src="image_preview.png";
function apply()
{
var reso = document.getElementById("resolution");
var resol = reso.options[reso.selectedIndex].value;
//alert(resol)
if (resol == "720p")
{
//alert("You changed to 720p");
h = 720;
w = 1280;
cheight = 720;
cwidth = 1280;
}
else if (resol == "480p")
{
//alert("You changed to 480p");
h = 480;
w = 640;
cheight = 480;
cheight = 640;
}
getSize();
redraw();
}
function redraw()
{
ctx.drawImage(img,w/2 - 14,h/2 - 19);
img.src="image_preview.png";
}
function getSize()
{
alert(h + "x" + w);
}

When using a canvas you have to ensure its internal structure has the same size of the rendering html zone.
You can do that :
this.canvas.width = this.canvas.clientWidth;
this.canvas.height = this.canvas.clientHeight;
Usually I also store those dimensions for my rendering computations :
var w = this.canvas.clientWidth; // stores the width for later use
var h = this.canvas.clientHeight;
this.canvas.width = w;
this.canvas.height = h;
EDIT : to change the element size, do this kind of thing before the precedent code :
$('#mycanvas').width(newWidthInPx);

Related

How to make a canvas text clickable/hoverable?

So I displayed text to the html canvas with c.fillText. I want to make it so that when I click/hover over the displayed text, a box will show up where we can input text. Is this possible?
var canvas = document.querySelector('canvas');
canvas.width = "1290";
canvas.height = "580";
var c = canvas.getContext("2d");
function ques() {
var question = document.getElementById("qInput").value;
//window.alert(question);
var randomColor = Math.floor(Math.random() * 16777215).toString(16);
var fontSize = Math.floor(Math.random() * 45 + 12);
var x = Math.floor(Math.random() * 1200);
var y = Math.floor(Math.random() * 580);
c.fillStyle = "#" + randomColor;
c.font = fontSize + "px Times New Roman";
c.fillText(question, x, y);
}
canvas {
/*
position: absolute;
top: 9%;
left: 2.5%;
*/
border: 1px solid #ddd;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<p class="title">Days in the Sun</p>
<canvas></canvas>
<!--for the search bar-->
<div class="search">
<input type="text" placeholder="Search.." name="search" id="qInput">
<button type="submit" onclick="ques()">
<i class="fa fa-search"></i>
</button>
</div>
If i understand you , you can do it with :
1)Make cursor pointer of the text with CSS.
canvas{
cursor:pointer;
}
2)Use javaScript.
document.getElementByTagName('canvas').addEventListener('click' , myFunction);
And in this function you can use javasript to change the DOM .If you want to be hovered replase "click" with mouseover ,but if you use mouse over you have to make another event on same element with "mouseout"
in such cases uses frameworks like Phaser/PIXI. But if you want make it by native canvas, hm:
You has x/y coordinates of your text(relatively to canvas element)(left and top x/y)
You can get right and bottom coordinates of text by using:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.measureText(text).width/height
now on click or on mousemove(hover analog) events, just compare the coordinates of the cursor(e.clientX, e.clientY) and the frame of the text, do they converge.
here is more descriptions with example, in link below:
HTML Canvas Hover Text

Draw More Arc Canvas

Hello People I'd Like to Know How to Draw More Arc Inside My Canvas, What I Need to Draw This circles:
So I Write This Responsive Code to Make my Canvas is Responsive:
var myCanvas = document.getElementById('myCanvas');
var ctx = myCanvas.getContext('2d');
var centerX = myCanvas.width / 2;
var centerY = myCanvas.height / 2;
var borderWidth = 20;
var borderColor = '#2DC36A';
var radius = (myCanvas.width / 2) - (borderWidth / 2);
// days arc canvas background
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.lineWidth = borderWidth;
ctx.strokeStyle = borderColor;
ctx.stroke();
ctx.closePath();
// Make Canvas Responsive
function makeResponsive() {
var containerWidth = $('.progress-nested').width();
$('.progress-nested').height(containerWidth);
var canvasElements = ['#myCanvas'];
$('#myCanvas').width(containerWidth).height(containerWidth);
}
makeResponsive(); // Make Canvas Responsive in Document ready
$(window).resize(function () {
makeResponsive(); // Make Canvas Responsive in Window Resize
});
#progress {
width: 100%;
padding: 5px;
}
.progress-nested{
position:relative;
border-radius:50%;
}
canvas {
display:block;
position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div id="progress">
<div class="container">
<div class="row">
<div class="col-xs-3 col-md-2 col-md-offset-2">
<div class="progress-nested">
<canvas id="myCanvas" width="250" height="250"></canvas>
</div>
</div>
</div>
</div>
</div>
Note: Please Run Code Snippet In Full Page

Javascript make an image bounce around screen

I have made code for a bouncing ball (using the arc() method on a canvas). I am wondering how to make an image bounce around the screen. Here is my previous code (note that the launchBall() function is going to be the function that runs the bouncing image):
<!DOCTYPE HTML>
<html>
<body onload="startBall()" oncontextmenu="return false;" style="cursor: none; overflow: hidden;">
<center>
<div id="div" style="width: 1600px; height: 700px; border: 2px solid #000000; background-color: grey;">
<br>
<img draggable="false"id="image" style="position: absolute;" width="50" height="50"src="http://www.clker.com/cliparts/b/a/b/0/1207156679935151925noxin_crosshairs.svg.hi.png"/>
</div>
<center>
<p>Score: <a>0</a></p>
</center>
<script>
var dx = 3;
var dy = 3;
var x = 100;
var y = 100;
var radius = 20;
var interval;
function startBall(){
interval = setInterval(launchBall, 20);
}
function launchBall(){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, 1275, 695);
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
document.getElementById
if(x<20 || x>1255) dx=-dx;
if(y<20 || y>675) dy=-dy;
x = x + dx;
y = y + dy;
}
document.getElementById("div").onmousemove = function(e) {
document.getElementById("image").style.top = e.pageY -25 + "px";
document.getElementById("image").style.left = e.pageX -25 +"px";
}
</script>
</body>
</html>

How to get width and height of canvas after resizing the browser

I want to get width and height of canvas which is responsive. I have 5 canvas elements on a single page.
Using Javascript before drawing I want to know the height and width of canvas to be able to draw images at the right size.
HTML Code:
<div id='container'>
<div class='all'>
<canvas id='clock1' style="border:solid">
</div>
<div class='all'>
<canvas id='clock2' style="border:solid">
</div>
<div class='all'>
<canvas id='clock3' style="border:solid">
</div>
<div class='all'>
<canvas id='clock4' style="border:solid">
</div>
<div class='all'>
<canvas id='clock5' style="border:solid">
</div>
</div>
CSS:
#container
{
width:100%;
height:100%;
position:relative;
}
.all
{
width:30%;
height:45%;
float:left;
}
canvas
{
width:100%;
height:100%;
}
Usually you don't set size of canvas using CSS but calculating the w/h and use the width and height properties.
But if you use CSS you can get the calculated size of the canvas element set by CSS using getComputedStyle():
Online demo
var cs = getComputedStyle(canvas);
var width = parseInt( cs.getPropertyValue('width'), 10);
var height = parseInt( cs.getPropertyValue('height'), 10);
the size is here returned by getPropertyValue() as a string and in pixel size (ie. "400px"), so we use parseInt() to chop of the "px" part.
Then simply set the width and height on canvas and update its content.
Full example (adjust as needed):
window.onresize = updateCanvas;
updateCanvas();
function updateCanvas() {
var cs = getComputedStyle(canvas);
var width = parseInt(cs.getPropertyValue('width'), 10);
var height = parseInt(cs.getPropertyValue('height'), 10);
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(width, height);
ctx.moveTo(0, height);
ctx.lineTo(width, 0);
ctx.stroke();
}

Using input type="range" to scale an image

What the title says. Is it possible? I want an image to scale up and down from it's center using a slider such as the input type="range".
Thanks in advance!
<input id="ranger" type="range" min="1" max="100" value="100" />
<hr />
<img id="image" src="http://google.com/images/logo.png" width="275" height="95" />
var ranger = document.getElementById('ranger'),
image = document.getElementById('image'),
width = image.width,
height = image.height;
ranger.onchange = function(){
image.width = width * (ranger.value / 100);
image.height = height * (ranger.value / 100);
}
Demo: http://jsfiddle.net/DnE83/1/
Study it, work out how it works.

Categories