I'm trying to draw a canvas with width x*100px and height y*100px
var x=6,y=5;
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
canvas.style.width=(100*x)+"px";
canvas.style.height=(100*y)+"px";
for(var i=0;i<x;i++)
for(var j=0;j<y;j++)
{
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (i*100, j*100, 100, 100);
ctx.fillStyle = "rgb(0,0,0)";
ctx.strokeRect(i*100, j*100, 100, 100);
}
jsfiddle
but it looks like the width and height of each tile in the grid are not 100 px, Why is that? and how can I set the width of each tile exactly to 100px?
Use this instead:
canvas.width=(100*x);
canvas.height=(100*y);
It seems a bit strange, but canvas is one element type that does not use CSS styling for its width and height. The number of available physical pixels is very relevant to the way that it draws, so it can't be left as a transient, derived CSS value (ie, width: calc(300vw - 100% - 20px);). That said, it's usually a good idea to have width/height change on a browser resize if you're making the web page responsive.
Related
I want to make an TIC TAC TOE and im pretty new to js. I want to draw the x's and 0's to the canvas.
1. How do I make the height equal to the width of the canvas?
2. What is the best way to scale the canvas to use this for example also on phones and have the same experience?
You can make a full-screen canvas and use it to display your code.
Here is a boilerplate to get you started:
HTML
<canvas id="canvas"></canvas>
CSS
* {
margin: 0;
}
canvas {
display: block;
}
JS
window.onload = function() {
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
width = canvas.width = window.innerWidth,
height = canvas.height = window.innerHeight;
context.fillRect(0, 0, width, height);
};
I'm trying to learn how to use HTML's Canvas and it's properties.
Now I'm trying to draw a ground and a sky, and I want the sky to be 75% of screens height and ground to be 25%.
This was easy using a div, and style it with CSS or JavaScript CSS Query. Now that I'm on a Canvas, I can't figure out how to set the fillRect properties...
My code:
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var skyHeight = windowHeight - (windowHeight * 0.25);
var groundHeight = windowHeight - (windowHeight * 0.75);
ctx = gameCanvas.getContext("2d");
ctx.fillStyle="green";
ctx.fillRect(0,0,windowWidth,windowHeight);
ctx.fillStyle="cyan";
ctx.fillRect(0,0,windowWidth,skyHeight);
Also: if I try using i.e.
ctx.fillStyle="cyan";
ctx.fillRect(0,0,30,30);
This draws a perfect square on top of the green "ground"-background, but if I change to i.e.
ctx.fillRect(0,0,200,200);
it will fill my entire height of the screen, and more than 50% of my screen-width.
According to http://www.w3schools.com/tags/canvas_fillstyle.asp canvas fillrect are using pixels, but 200 x 200 pixels should definitely NOT fill my entire screen height. :/
Where's the part where you tell canvas what its dimensions are? Just like any other HTML media element that you need to be of a specific size (video, image), you need to tell it what its width and height is if you want reliably sized content (if you don't, by convention the canvas will be sized 300 x 150px). And because we're setting the number of pixels we can draw on, this is not "purely cosmetic" like CSS, we have to do it properly:
var cvs = document.querySelector("canvas");
// if you didn't use <canvas width="..." height="...">, we need this:
cvs.width = 800;
cvs.height = 400;
And then you can do your drawing:
var ctx = cvs.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0,0.75*cvs.height, cvs.width,0.25*cvs.height);
ctx.fillStyle = "lightblue";
ctx.fillRect(0,0, cvs.width, 0.75*cvs.height);
See http://jsbin.com/tejiqixeji/edit?html,js,output
How do I use drawImage() to output full size images on a 300px X 380px canvas regardless of the source image size?
Example:
1). If there is a image of 75px X 95px I want to be able to draw it to fit a 300px X 380px canvas.
2). If there is a image of 1500px X 1900px I want to be able to draw it to fit a 300px X 380px canvas.
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("myPic");
ctx.drawImage(img,10,10);
What options are available to prevent any quality loss?
To scale the image to fit is not so hard, just use simple aspect ratio with the sizes:
var ratioX = canvas.width / image.naturalWidth;
var ratioY = canvas.height / image.naturalHeight;
var ratio = Math.min(ratioX, ratioY);
ctx.drawImage(image, 0, 0, image.naturalWidth * ratio, image.naturalHeight * ratio);
To maintain quality; a canvas of 300x380 will either appear very tiny on print, or very blurry.
It's important to keep the data from it in the target resolution. To do this, calculate the size using the target DPI (or rather, PPI). You will also need to know in advance what size the 300x380 area represents (e.g. in either inches, centimeters, millimeters etc.).
For example:
If the target PDF will have a PPI of 300, and the canvas represents 3 x 3.8 cm (just to keep it simple), then the width and height in pixel will be:
var w = (3 / 2.54) * 300; // cm -> inch x PPI
var h = (3.8 / 2.54) * 300;
Use this size on canvas' bitmap, then scale down the element using CSS:
canvas.width = w|0; // actual bitmap size, |0 cuts fractions
canvas.height = h|0;
canvas.style.width = "300px"; // size in pixel for screen use
canvas.style.height = "380px";
You can now use the canvas directly as an image source for the PDF while keeping print quality for the PDF (have in mind though, small images uploaded will not provide high print quality in any case).
And of course, set the canvas size first, then use the code at top to draw in the image.
You'll need to resize your source image. You will need to calculate the destination size of the image, then use a couple extra parameters during your draw.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = 188;
var y = 30;
var width = 200;
var height = 137;
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, x, y, width, height);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
body {
margin: 0px;
padding: 0px;
}
<canvas id="myCanvas" width="578" height="200"></canvas>
Source: http://www.html5canvastutorials.com/tutorials/html5-canvas-image-size/
I get a wrong canvas height. Whats wrong here?
I made a fiddle: http://jsfiddle.net/hbcz6/
HTML:
<div id="app">
<div id="percent" class="animated"></div>
<canvas></canvas>
</div>
Javascript:
var canvas = document.getElementsByTagName("canvas")[0];
var context = canvas.getContext('2d');
var x = canvas.width / 2;
console.log("canvas X: ", x);
var y = canvas.height / 2;
console.log("canvas y: ", y);
Please have a look to your console.
As you are not setting the size of the canvas element its bitmap will default to 300 x 150 pixels. If you use CSS rules then the element will be stretched but the bitmap will, stay at the same size just scaled to fit the size of the element (just like an image would).
Here is how to dynamically fit a canvas element inside a parent element settings its size properly:
First, remove the width and height from the CSS rule:
#app canvas {
border:2px solid red;
}
Then use getComputedStyle to get the parent element's dimension in pixels:
var cs = getComputedStyle(app),
width = parseInt(cs.getPropertyValue('width'), 10);
height = parseInt(cs.getPropertyValue('height'), 10);
The parseInt will remove the px at the end - now simply use those for the canvas element:
canvas.width = width;
canvas.height = height;
Working fiddle here
You aren't setting the canvas's dimensions. Using CSS to style it only affects the rendered result, it does not affect the underlying canvas that is being drawn on. In this case, it is using the default sizes, and then stretching it to cover the container.
I am using javascript to draw a rectangle around DOM elements in a website.
The problem is that the rectangles are drawn in the wrong positions.
I know that canvas, work like a real canvas so you have to "predraw" everything before filling the canvas, otherwise the elements will be on top of each other, in the orders you drew them.
That's why I'm defining canvas, and context outside of the loop.
This is my code:
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.globalAlpha = 0.5;
//Set canvas width/height
canvas.style.width='100%';
canvas.style.height='100%';
//Set canvas drawing area width/height
canvas.width = document.width;
canvas.height = document.height;
//Position canvas
canvas.style.position='absolute';
canvas.style.left=0;
canvas.style.top=0;
canvas.style.zIndex=100000;
canvas.style.pointerEvents='none'; //Make sure you can click 'through' the canvas
document.body.appendChild(canvas); //Append canvas to body element
var listingsRect = Array.prototype.map.call(document.querySelectorAll('.rc'), function(e) {
return e.getBoundingClientRect();
});
listingsRect.forEach(function(listingRect) {
var x = listingRect.left;
var y = listingRect.top;
var width = listingRect.width;
var height = listingRect.height;
//Draw rectangle
context.rect(x, y, width, height);
context.fillStyle = 'yellow';
context.fill();
});
However, when I change
canvas.width and canvas.height to window.innerWidth and window.innerHeight respectively, then canvas draws the rectangles in the right positions, however it only draws them in the visible area of the website (obviously).
Can somebody tell me what's wrong with my code?
Here's a JS bin:
http://jsbin.com/elUToGO/1
The x,y in context.rect(x,y,width,height) are relative to the canvas element not to the browser window.
So if your canvas element is absolutely positioned at 50,75 and you want a rect at window position 110,125 you would draw your rect like this:
context.rect( 110-50, 125-75, width, height );
A few other things:
If you set the canvas element width/height and then position absolutely, you don't need canvas.style.width/height.
document.width/height are deprecated (& not supported in IE) . Use this instead:
//Set canvas drawing area width/height
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
When setting style.left/top, you might want to pass a string with "px" in case you later set >0.
canvas.style.left="0px";
canvas.style.top="0px";
.pointerEvents='none' is supported in most browsers (but not in IE<11)