I try to draw a circle in the middle of the device browsers width and height. But the canvas element disturb. The circle become draw in the middle of the devices width and height, if I make the canvas big enough, but the canvas size should fit in the device size.
Is there any way to fit the canvas width and height the device width and height?
thats the solution:
<html>
<head>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1">
<style>
/* Remove padding and margin */
* {
margin:0;
padding:0;
}
html, body, .myCanvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="myCanvas" class="myCanvas"/>
<script>
var canvas = document.getElementById('myCanvas');
var width = canvas.width;
var height = canvas.height;
var context = canvas.getContext('2d');
var centerX = width / 2;
var centerY = height / 2;
var radius = 70;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#FF3300';
context.stroke();
console.log("width: " + width);
console.log("height: " + height);
</script>
</body>
</html>
Just add this to your code, right after getting the canvas:
canvas.width = width;
canvas.height = height;
You can also remove width and height attributes from the html part
Use css % size
HTML:
<canvas id="myCanvas" class="myCanvas"/>
CSS:
/* Remove padding and margin */
* {
margin:0;
padding:0;
}
html, body, .myCanvas {
width: 100%;
height: 100%;
}
Edit:
Get the width/height of your canvas instead of the window.
<html>
<head>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1">
<style>
/* Remove padding and margin */
* {
margin:0;
padding:0;
}
html, body, .myCanvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="myCanvas" class="myCanvas"/>
<script>
var canvas = document.getElementById('myCanvas');
var width = canvas.width;
var height = canvas.height;
var context = canvas.getContext('2d');
var centerX = width / 2;
var centerY = height / 2;
var radius = 70;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#FF3300';
context.stroke();
console.log("width: " + width);
console.log("height: " + height);
</script>
</body>
</html>
Related
I am trying to create a painting app using HTML canvas. I want to implement zoom and panning functionality to the canvas.
The user should be able to paint on the canvas, then zoom in or out(which scales the already drawn elements) and pan(which translates the elements) and then draw over them.
Currently, I am stuck at implementing zoom properly.
Solutions explored:
ctx.scale will scale the canvas but not the already painted elements. New elements are drawn with a scaled effect and away from the cursor.
Storing the canvas in another temporary canvas. Then redrawing the original canvas with scaled temporary canvas. This results in pixelation when zoomed in and so is not desired.
tempCtx.drawImage(canvas, 0, 0);
ctx.drawImage(tempCanvas, 0, 0, cw, ch, 0, 0, cw *scaleFactor, ch * scaleFactor);
CODE:
window.addEventListener('load', () => {
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
let penColor = "#2525c5";
let brushSize = 4;
const zoomInBtn = document.querySelector("#zoom-in");
const zoomOutBtn = document.querySelector("#zoom-out");
let scaleFactor = 1;
zoomInBtn.addEventListener("click", () => {
scaleFactor = scaleFactor * 1.1;
ctx.scale(scaleFactor, scaleFactor);
});
zoomOutBtn.addEventListener("click", () => {
scaleFactor = scaleFactor * 0.9;
ctx.scale(scaleFactor, scaleFactor);
});
let painting = false;
function startPosition(e) {
painting = true;
draw(e);
}
function finishedPosition() {
painting = false;
ctx.beginPath();
}
function draw(e) {
if (!painting) return;
ctx.lineWidth = brushSize;
ctx.strokeStyle = penColor;
ctx.lineCap = "round";
let rect = e.target.getBoundingClientRect();
let x = e.clientX - rect.left;
let y = e.clientY - rect.top;
ctx.lineTo(x, y);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x, y);
}
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", finishedPosition);
canvas.addEventListener("mousemove", draw);
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#toolbar {
display: flex;
}
.tool-group {
display: flex;
margin-right: 40px;
}
#canvas-container {
box-sizing: border-box;
margin-top: 50px;
margin-left: 50px;
width: 500px;
height: 500px;
border: 2px solid black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="style.css" />
<title>Drawing App</title>
</head>
<body>
<div id="app">
<div id="toolbar">
<div class="tool-group">
<button id="zoom-in">Zoom in</button>
<button id="zoom-out">Zoom out</button>
</div>
</div>
<div id="canvas-container">
<canvas id="canvas" width="500" height="500"></canvas>
</div>
</div>
<script src="canvas2.js"></script>
</body>
</html>
i am trying to get the rgb color data from a painted canvas.
with this function:
function pick(event) {
var x = event.layerX;
var y = event.layerY;
var pixel = ctx.getImageData(x, y, 1, 1);
var data = pixel.data;
$("#color").val(pixel.data.toString());
console.log(pixel.data.toString());
}
however, when i am setting the canvas element to any relative width (80%/100%), like this:
canvas {
/*width: 100%;*/ /*when i set the width, the rgb values are incorrect .... */
/*margin-left: auto;
margin-right: auto;
display: block;*/
}
i am no longer getting correct values from this function.
attaching my JS Fiddle:
https://jsfiddle.net/iliran11/ay9nf1p9/
You need to find the difference in width when you stretch and multiply that to the coordinates.
//color names
var basecolors = ["(255,0,0)",
"(255,128,0)",
"(255,255,0)",
"(128,255,0)",
"(0,255,0)",
"(0,255,128)",
"(0,255,255)",
"(0,128,255)",
"(0,0,255)",
"(128,0,255)",
"(255,0,255)",
"(255,0,128)",
"(128,128,128)"
];
//init
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var heightPerColor = height / basecolors.length;
//init cursor
var xCursor = 0;
var yCursor = 0;
drawPallete(width, height, "s");
function drawPallete(width, height, type) {
canvas.width = width;
canvas.height = height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var Grad = ctx.createLinearGradient(0, 0, canvas.width, 0);
Grad.addColorStop(0 / 6, '#F00');
Grad.addColorStop(1 / 6, '#FF0');
Grad.addColorStop(2 / 6, '#0F0');
Grad.addColorStop(3 / 6, '#0FF');
Grad.addColorStop(4 / 6, '#00F');
Grad.addColorStop(5 / 6, '#F0F');
Grad.addColorStop(6 / 6, '#F00');
ctx.fillStyle = Grad;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
;
function pick(event) {
var canvas = document.getElementById("canvas");
//Here comes the stretch offset
//var off = (1 / canvas.width) * canvas.offsetWidth;
var off = (1 / canvas.offsetWidth) * canvas.width;
//Applying offset
var x = Math.floor(event.layerX * off) - Math.floor(canvas.offsetLeft * off);
var y = Math.floor(event.layerY * off) - Math.floor(canvas.offsetTop * off);
var pixel = ctx.getImageData(x, y, 1, 1);
var data = pixel.data;
$("#color").val([pixel.data[0], pixel.data[1], pixel.data[2], pixel.data[3]].join(','));
//console.log("offset between", canvas.width, "and", canvas.offsetWidth, "is", off);
console.log(off, canvas.offsetWidth, canvas.width, x);
}
// target the button
var btn = $("#myBtn");
var modal = $("#myModal");
btn.click(function () {
modal.css("display", "block");
var canvas = document.getElementById("canvas");
canvas.addEventListener('mousemove', pick);
});
#myModal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
canvas {
width: 100%;
/*margin-left: auto;
margin-right: auto;
display: block;*/
}
<form action="" method="post">
<label for="POST-name">Name:</label>
<input id="color" type="text">
</form>
<button id="myBtn">Open Color</button>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<!-- Set height and width -->
<canvas id="canvas" width="1000" height="1000"></canvas>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
EDIT 1
Compensated for offsetLeft and offsetTop.
I managed to put together a dynamically resizing HTML5 Canvas but it has issues. For instance, it only scales the height, not the width too. My canvas has width of 900px and height of 850px. Another issue is that it enlarges the canvas too, way beyond it's defined width and height.
What am I doing wrong?
Here's what I tried so far:
var canvas, stage, exportRoot;
function init() {
createjs.MotionGuidePlugin.install();
canvas = document.getElementById("canvas");
exportRoot = new lib.Hat_finale();
stage = new createjs.Stage(canvas);
stage.addChild(exportRoot);
stage.update();
createjs.Ticker.setFPS(24);
createjs.Ticker.addEventListener("tick", stage);
}
function resize() {
var height = window.innerHeight;
var ratio = canvas.width / canvas.height;
var width = height * ratio;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
}
window.addEventListener('load', resize, false);
window.addEventListener('resize', resize, false);
#container {
margin: 0 auto;
max-width: 900px;
max-height: 850px;
}
<div id="container">
<canvas id="canvas" width="900" height="850" style="background-color:#ffffff"></canvas>
</div>
UPDATE:
If I try what #havex said, changing the attributes like so: canvas.width = width; and canvas.height = height; instead of canvas.style.width = width+'px'; and canvas.style.height = height+'px'; what I get is a resizable box BUT NOT the animation. See picture for reference :
I can't explain why that is happening because it's 4:30 in the morning and I haven't slept yet, but change these and it should work (you can remove the borders):
HTML
<div id="container">
<canvas id="canvas" style="background-color:#ffffff"></canvas>
</div>
CSS
#container{
margin:0 auto;
width:900px;
height:850px;
border: 1px solid black;
}
canvas { width: 900px; height: 850px; border: 1px solid red; }
http://jsfiddle.net/Ln5z1zab/
Hello I am lilbit new to Javascript and Jquery.
i want to move earth(image) around sun(image) but i dont want to use any jQuery-plugin.
I have tried few Option but it is not working.
So If there is anyway(i guess it is) then plz answer.
Thanks in Advance
<html>
<head>
<style type="text/css">
body {
background-color: ivory;
}
canvas {
position:absolute;
left:15%;
top:5%;
margin-left:center;
margin-top:center;
background-color:black;
border:1px solid red;
}
#Aditya{
position:relative;
top:25%;
left:20%;
}
</style>
<script type="text/javascript" src="js/Jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var canvas = document.getElementById("icanvas");
var ctx = canvas.getContext("2d");
var radianAngle = 0;
var cx = 400;
var cy = 400;
var radius = 230;
var img = document.getElementById("myearth");
img.height="5px";
img.width="5px";
img.onload = start;
function start() {
animate();
}
function animate() {
requestAnimationFrame(animate);
// Drawing code goes here
radianAngle +=Math.PI / 120;
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw the image rotated around the circumference
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(radianAngle);
ctx.drawImage(img, radius - img.width / 2, -img.height/2);
ctx.restore();
}
});
</script>
</head>
<body>
<canvas id="icanvas" width="800px" height="800px">
<img src="earth.jpg" alt="earth" id="myearth" width="50%" height="50%"></img>
<img src="sun.jpg" alt="Sun" id="Aditya"></img>
</canvas>
</canvas>
</body>
sorry for delay to upload code.only earth is moving into canvas.dont know how to put sun in center.
Thank you all to showing interest.But i finally did it.perhaps you would like to see.
<html>
<head>
<style type="text/css">
body {
background-color: ivory;
}
canvas {
position:absolute;
left:15%;
top:5%;
margin-left:center;
margin-top:center;
background-color:black;
border:1px solid red;
}
.sunimg{
position:absolute;
left:40%;
top:40%;
}
</style>
<script type="text/javascript" src="js/Jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#Aditya").addClass("sunimg");
var canvas = document.getElementById("icanvas");
var ctx = canvas.getContext("2d");
var radianAngle = 0;
var cx = 400;
var cy = 400;
var radius = 230;
var img = document.getElementById("myearth");
img.height="5px";
img.width="5px";
img.onload = start;
function start() {
animate();
}
function animate() {
requestAnimationFrame(animate);
// Drawing code goes here
radianAngle +=Math.PI / 120;
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw the image rotated around the circumference
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(radianAngle);
ctx.drawImage(img, radius - img.width / 2, -img.height/2);
ctx.restore();
}
});
</script>
</head>
<body>
<canvas id="icanvas" width="800px" height="800px">
<img src="earth.jpg" alt="earth" id="myearth" width="50%" height="50%"></img>
</canvas>
<img src="sun.jpg" alt="Sun" id="Aditya"></img>
</body>
In Java script I am changing the height and width of the HTML5 canvas. It works in Mozila, Chrome, opera and safari, But it is not working in IE9. Can any body tell me what I am doing wrong, do I need to set any property?
Thanks in advance
UPDATE:-
HTML:-
<body onload="Load();">
<canvas id="myCanvas" width="500" height="300"></canvas>
</body>
Javascript:-
function Load(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
img=new Image();
img.src= "data:image/bmp;base64,"+respObj.respData; //Adding bmp image header
img.onload = function(){
canvas.width = 300;
canvas.height = 500;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(img,0,0,canvas.width, canvas.height);
}
}
CSS:-
.canvas{
height: auto;
width: auto;
margin : 0px 35px;
border:1px solid black;
position: relative;
}
Try the following code. It is working in IE9, Firefox, Chrome :
<!DOCTYPE html>
<html>
<style language="css/text">
.canvas{
height: auto;
width: auto;
margin : 0px 35px;
border:1px solid black;
position: relative;
}
</style>
<body onload="Load();">
<canvas id="myCanvas" width="500" height="300"></canvas>
<input type="button" onClick="change()"/>
</body>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
function Load(){
img=new Image();
//img.src= "data:image/bmp;base64,"+respObj.respData; //Adding bmp image header
canvas.width = 300;
canvas.height = 500;
context.fillStyle="#FF0000";
context.fillRect(0, 0, canvas.width, canvas.height);
//context.drawImage(img,0,0,canvas.width, canvas.height);
}
function change() {
canvas.width = 100;
canvas.height = 100;
context.fillStyle="#FF0000";
context.fillRect(0, 0, canvas.width, canvas.height);
}
</script>
</html>
I found the issue with my canvas. It was the issue with style. I have removed the height and width setting from the style script. Because of it, the canvas height and width was overriding to its default values i.e. 150 and 300 as height and width respectively.