I am drawing on a canvas object using JavaScript and somehow Internet Explorer (don't ask, I have to), Version 11 scales the drawings along the x axis.
Here is the JavaScript code:
var c = document.getElementById('canvas1');
var ctx = c.getContext('2d');
ctx.beginPath();
ctx.arc(50, 50, 50, 0, 2 * Math.PI);
ctx.fillStyle = '#000000';
ctx.lineWidth = 5;
ctx.stroke();
You would expect a circle to appear. But instead I get an Ellipse:
(Don't mind the horizontal line on the left, that just the surrounding div. The canvas is the small square.)
EDIT: The size of the canvas is 100 x 100.
Following the comments the answer is to set height and width of the canvas object as attributes of the canvas-tag. Like this:
<canvas height="200" width="400"></canvas>
See this post for further explanation.
Related
I'm trying to place text on sqlare rotated 45 degrees. The problem is my text is under the rectangle shape. Can I change position of text?
my code is like
var c = document.getElementById("myCanvas");
var square= c.getContext("2d");
var text= c.getContext("2d");
text.fillStyle = "red";
text.fillText("1", 40, 50);
text.fillStyle = "#000000";
square.rotate(Math.PI / 4);
square.fillRect(50, 0, 50, 50);
jsfiddle
You're drawing the text first, then the rectangle, and then wondering why the text is behind the rectangle?
Firstly, you only need to getContext once, not twice.
Second, draw things in the right order: background first, then foreground.
It appears you may have a misconception about how the canvas context works.
You see, you only need one instance of the context, which you can then use to create all your shapes, paths and even write text on the canvas.
Also, you are drawing the text before the rectangle, which would cover it up.
With that in mind, I've created a new JSFiddle where you can check out a correct approach to do this.
HTML
<canvas id="myCanvas" width="300" height="150">
Your browser does not support the HTML5 canvas tag.
</canvas>
JavaScript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d"); //we get the canvas context
ctx.save(); //save context properties
ctx.rotate(Math.PI / 4);
ctx.fillRect(50, 0, 50, 50);
ctx.restore(); //restore saved properties
ctx.fillStyle = "red";
ctx.fillText("1", 40, 50);
As you can see, we only take one instance of the context, and we draw from there.
The context save() and restore() functions help prevent the rotation from affecting the text. You could also rotate the same amount in the opposite direction.
Hope it helps!
I'm just started working with Leap Motion (it is so much fun). The Leap works mainly with vectors. And now I want to create a program where I can visualise where is a vector pointing. The only way I can imagine doing this is by using a small image which appears when this fuction is on and positioning by using the img.style.left , img.style.top instructions. Any other ideas?
If your goal is to represent 2D Vectors,
You can use canvas to draw lines.
A canvas is like a div but you can draw whatever you want in it, I don't know anything about Leap Motion but if you want to draw lines and circles at precise coordinates, it may be a good solution instead of working with the DOM itself.
The JS part looks like this :
var canvas = document.getElementById('my-canvas');
var ctx = canvas.getContext('2d');
//For exemple here is how to draw a rectangle
//fillStyle support all valid css color
ctx.fillStyle = "rgba(50, 255, 24, 0.7)";
//Create the rectangle, with (startX, startY, height, width)
ctx.fillRect(20, 15, 50, 50);
ctx.beginPath(); //Tells canvas we want to draw
ctx.moveTo(250,250); //Moves the cursor to the coordinates (250, 250);
ctx.lineTo(75, 84); //Draws a line from the cursor (250, 250) to (75, 84);
ctx.closePath(); //Tells canvas to 'close' the drawing
ctx.strokeStyle = "red";
ctx.stroke(); //Draws the line stroke
And the HTML is simply :
<canvas id="my-canvas" height="500px" width="500px">
Here is the text displayed when the browser doesnt support canvas.
</canvas>
I made a jsfiddle to show you what simple things we can do with canvas.
http://jsfiddle.net/pq8g0bf0/1/
A nice website to learn canvas : http://www.html5canvastutorials.com/tutorials/html5-canvas-element/
Since it's javascript, you are free to do calculations for your vectors coordinates, addding eventListeners etc ...
Playing with HTML5 canvas and JS, I found a strange behaviour when a canvas is added to the HTML body directly versus creating a canvas using JS.
<!DOCTYPE html>
<html>
<head></head>
<body>
<canvas id="test" width="200" height="200" style="border:1px solid #000000;">
</canvas>
<script>
var c=document.getElementById("test");
ctx=c.getContext("2d");
ctx.fillStyle = "#9ea7b8";
ctx.fill();
ctx.moveTo(0,0);
ctx.lineTo(200,200);
ctx.stroke();
// creating canvas using JS
c = document.createElement("canvas");
c.id="MyCanvas";
c.style.width="200px";
c.style.height="200px";
c.style.border="1px solid #000000";
ctx=c.getContext("2d");
ctx.fillStyle = "#9ea7b8";
ctx.fill();
ctx.moveTo(0,0);
ctx.lineTo(200,200);
ctx.stroke();
document.body.appendChild(c);
</script>
</body>
</html>
Please see the code & ouput here
I expected the line (stroke) to be a consistent diagonal across the canvas but alas!. Please help me know where am I going wrong!
Note: I forgot to mention, I tried this on Chrome only not sure if the behaviour is consistent for other browsers.
So, basically if you change from style to attribute it works.
Why ?
It seems that the width and height attributes determine the width or height of the canvas's coordinate system, whereas the CSS properties just determine the size of the box in which it will be shown.
Source
Like this it will work fine:
var c = document.getElementById("test");
ctx = c.getContext("2d");
ctx.fillStyle = "#9ea7b8";
ctx.fill();
ctx.moveTo(0, 0);
ctx.lineTo(200, 200);
ctx.stroke();
// creating canvas using JS
c = document.createElement("canvas");
c.id = "MyCanvas";
c.setAttribute("width", "200px")
c.setAttribute("height", "200px")
c.style.border = "1px solid #000000";
ctx = c.getContext("2d");
ctx.fillStyle = "#9ea7b8";
ctx.fill();
ctx.moveTo(0, 0);
ctx.lineTo(200, 200);
ctx.stroke();
document.body.appendChild(c);
<canvas id="test" width="200" height="200" style="border:1px solid #000000;"></canvas>
Canvas width and height attributes are not the same as its CSS width and height. Setting canvas.width/height attributes determines the total drawable pixel area, which can be (but does not need to be) scaled with CSS to be larger or smaller on the screen.
Normal scenario: Make canvas attribute bounds larger than CSS bounds
In fact, to make a high density display canvas it is necessary to set canvas.width and canvas.height twice as large as the css. In other words you might do:
// Two canvas pixels per screen pixel so it looks nice
// on a high density (in this case pixel ratio: 2) display
canvas.width = 800;
canvas.height = 800;
canvas.style.width = '400px';
canvas.style.height = '400px';
Normal scenario: Make canvas attribute bounds smaller than CSS bounds
On the flip side in order to make some apps like games fast canvas.width and canvas.height might be restricted to 640x480 (or something small) and then scaled with CSS to take up the whole screen. Since the total number of pixels handled on the canvas is small, the game will be faster than if you used a really large canvas and filled the screen. Obviously the game will look different, since CSS will be scaling the graphics (for better or worse).
I'm trying to draw an object based on it's rotate property, but it seems to get confused when the object is moving.
ctx.save();
ctx.translate(this.width * 0.5, this.height*0.5);
ctx.rotate(DegToRad(45));
ctx.translate(-this.width*0.5,-this.height*0.5);
ctx.drawImage(this.img, this.spriteOffset, 0, this.width, this.height, this.x, this.y,this.width,this.height);
ctx.restore();
The image is drawn rotated 45 degrees, however it now moves in a down-left direction, when the object should only be moving downwards. The movement code is simply handled by incrementing the this.y position. Is there a simpler way to accomplish this?
This is because the whole canvas is being rotated.
What you could try is looking into a framework like Kinetic JS, which creates a sort of SVG API for the canvas.
This site has tons of information on how to use it as well, including rotation, transition, transformation, and pretty much anything else that you might need in working with it.
This should suit your needs rather well.
I think I should provide a low-level, framework-free option as well. Basically, using raw javascript and HTML to pull this off.
Now, as I understood your question, you are trying to make an object (let's assume a black square) move downwards AND have it spin. The only way I can think of to spin it in the canvas without going into path hell is to rotate the entire rendering context. BUT you can also import an image into canvas, for instance, a transparent black diamond (i.e. that same square rotated). So you'd use a separate canvas to render each step of the rotation for the square.
Essentially something like this:
var canvas2 = document.createElement('canvas'), ctx2 = canvas2.getContext('2d');
//do something with the second canvas
//let's assume the second canvas is the same size as the square
ctx.drawImage(canvas2, squareX, squareY);
See my attempt
As you can see, it is a bit wonky, but it does do essentially what the question asks; it moves the square down, and rotates it. It also plots the result of that rotation below the actual canvas so you can see what's happening under the hood, but the square cuts out due to the "center" being on the top left of the square, and not in the middle.
In the end, it really comes down to how you want to do it.
I was playing around with the API and found it was easier to just keep track of where the object should be. here's an example of a square moving diagonally across the screen and rotating.
<canvas id="canvas" style="width: 100%; height: 100%;">
</canvas>
<script>
var DELAY = 15; // ms
var RECT_WIDTH = 100; // px
var RECT_HEIGHT = 100; // px
var canvas = document.getElementById('canvas');
// set intrinsic dimensions
canvas.width = 1000;
canvas.height = 1000;
var ctx = canvas.getContext('2d')
ctx.fillStyle = 'teal';
var step = 0
var vx = 2
var animate = setInterval(function () {
ctx.resetTransform()
ctx.clearRect(0, 0, 1000, 1000);
ctx.translate(vx * step, vx * step);
// rotation in place, translate to center of square and back
ctx.translate(RECT_WIDTH / 2, RECT_HEIGHT / 2);
ctx.rotate((Math.PI / 180) * step);
ctx.translate(-(RECT_WIDTH / 2), -(RECT_HEIGHT / 2));
// Draw the rectangle
ctx.fillRect(0, 0, RECT_WIDTH, RECT_HEIGHT);
step = step + 1
}, DELAY)
setTimeout(function () {
clearInterval(animate);
}, 5000);
</script>
Here, I use vx and keep track of the steps to translate, and calculate what the rotation will be in radians based on the steps a new not caring what the previous state was. Make sure you rotate across the center of where you're square will be as well.
Use ctx.translate to set the object's position before applying the rotation. This should fix the problem.
ctx.save();
ctx.translate(this.x, this.y);
ctx.translate(this.width * 0.5, this.height*0.5);
ctx.rotate(DegToRad(45));
ctx.translate(-this.width*0.5,-this.height*0.5);
ctx.drawImage(this.img, this.spriteOffset, 0, this.width, this.height, 0, 0,this.width,this.height);
ctx.restore();
So I have a rotating canvas element which has an arc drawn inside it (the smaller planet):
http://jsfiddle.net/neuroflux/9L689/4/ (updated)
But I can't seem to get the anti-aliasing on the edges of the smaller planet smoother - any ideas?
Cheers!
edit: is there a way to increase the number of iterations used within an arc?
Your problem is not that the arc doesn't have enough points, but that in Chrome the .clip() operation doesn't use anti-aliasing to produce the clipping path.
See Chromium Issues 7508 and 132442
To see this in action, look at http://jsfiddle.net/alnitak/YMtdZ/ in Chrome.
markup:
<canvas id="c" width="600" height="300" />
code:
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.save();
ctx.beginPath();
ctx.arc(150, 150, 140, 0, 2 * Math.PI);
ctx.clip();
ctx.fillRect(0, 0, 600, 300);
ctx.restore();
ctx.beginPath();
ctx.arc(450, 150, 140, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
The left-hand circle is drawn with clipping, and is aliased. The right-hand circle is drawn "normally", and is anti-aliased.
FWIW, in Firefox and Safari both images look the same. I can't test it on IE.
The only work around I can imagine (until Chrome gets fixed) would be to render the image off-screen into a canvas 3 or 4 times larger, and then copy that with down-sampling into the displayed canvas.