Canvas Element - Rotation - javascript

I've multiple canvas elements, each one work on his own. I would like to use these to create a multiplayer. It works perfectly, but now I would like to rotate single canvas elements (180 degree). I tried the getContext('2d') method but it only helps me for a single obeject on the canvas. But what I would like to do is to rotate the WHOLE canvas.
Does someone know how I can do this?
Feilx

You could utilize CanvasRenderingContext2D.rotate() and CanvasRenderingContext2D.translate methods for that purpose, the following example illustrates it:
var canvas = document.getElementById("canvas");
var angleInput = document.getElementById("angleInput");
canvas.width = 800;
canvas.height = 600;
var ctx = canvas.getContext("2d");
var angleInDegrees=0;
drawRotated(ctx,angleInDegrees);
document.getElementById("clockwiseButton").addEventListener('click',function(){
angleInDegrees+=parseInt(angleInput.value);
drawRotated(ctx,angleInDegrees);
});
document.getElementById("counterclockwiseButton").addEventListener('click',function(){
angleInDegrees-=parseInt(angleInput.value);
drawRotated(ctx,angleInDegrees);
});
function drawRotated(ctx,degrees){
var canvasWidth = ctx.canvas.width;
var canvasHeight = ctx.canvas.height;
ctx.clearRect(0,0,canvasWidth,canvasHeight); // Clear the canvas
ctx.save();
ctx.translate(canvasWidth/2,canvasHeight/2); // Move registration point to the center of the canvas
ctx.rotate(degrees*Math.PI/180); // Rotate
drawObjects(ctx);
ctx.restore();
}
function drawObjects(ctx)
{
//draw triangle
ctx.beginPath();
ctx.moveTo(200,150);
ctx.lineTo(150,200);
ctx.lineTo(250,200);
ctx.fill();
//draw circle
ctx.beginPath();
ctx.arc(350,75,50,0,Math.PI*2,false);
ctx.fill();
ctx.stroke();
//draw rectangle
ctx.fillRect(50,50,150,50);
}
<div>
<button id="clockwiseButton">Rotate right</button>
<button id="counterclockwiseButton">Rotate left</button>
<input id="angleInput" value="45"></input>
</div>
<canvas id="canvas"></canvas>
JSFiddle

Related

Is there a way to rotate a <canvas> element and treat the input as its rotated value?

I have a canvas with ID foobar. I've already drawn to it.
let canvas = document.getElementById("foobar");
I need to rotate this canvas 90°. Rotating #foobar with CSS doesn't work:
#foobar {
/* When I click somewhere on the canvas, it registers the position of the click
as what the position would be pre-rotation rather than post-rotation. */
transform: rotate(90deg);
}
In addition, rotating the context only works when an element has yet to be drawn, so this won't work either:
let context = canvas.getContext("2d");
context.rotate(90 * (Math.PI / 180));
When registering clicks, try to use event.offsetX and event.offsetY. These should line up properly with the canvas coordinates. For example:
<canvas>
</canvas>
<style>
canvas {
transform: rotate(90deg);
/* just so the canvas is visible */
border-color: black;
border-style: solid;
}
</style>
<script>
// when canvas is clicked, draw a dot
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
canvas.addEventListener('click', (e) => {
const x = e.offsetX;
const y = e.offsetY
ctx.beginPath();
ctx.arc(x, y, 10, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
});
</script>

How can I change line width in a canvas in HTML with a click event in JavaScript

I want to change the line width in canvas from 5 to 10 from a click event but it's not working in JavaScript
function draw(e) {
if (!painting) {
return;
}
exitdraw(e);
c.lineWidth = 5;
c.lineTo(e.clientX, e.clientY);
c.lineCap = 'round';
c.strokeStyle = 'aqua';
c.stroke();
c.beginPath();
c.moveTo(e.clientX, e.clientY);
}
//this is the listener i want to change the linewidth
var canvas = document.querySelector('#canvas');
var btn = document.getElementById('button');
btn.addEventListener('click',function(){
canvas.getContext('2d').lineWidth = 10;
})
<button onclick="changeWidth()">Change Width</button>
<br />
<canvas height="150" id="canvas" width="200"></canvas>
<script>
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var lineWidth = 5;
function draw() {
ctx.beginPath();
ctx.lineWidth = lineWidth;
ctx.arc(100, 75, 32, 0, 2 * Math.PI);
ctx.stroke();
}
draw();
function changeWidth() {
lineWidth = 10;
draw();
}
</script>
Canvas doesn't store references to what you draw on it so it's impossible to change property that will affect what you draw.
What I mean is in order to change some drawing in your canvas you should render it again with your new style.
Because you use client data on your draw function you should store the data (clientX/Y etc...) in variables (or you may prefer one object that stores all data) and call that function again, but you need to refactor your function to get lineWidth as a param.
Trouble is, you are changing the value after content is drawn. For changes to take affect, you may want to redraw the content after a change. Like:
btn.addEventListener('click',function(){
canvas.getContext('2d').lineWidth = 10;
draw(); // apply changes by redrawing
})
And of course you should omit the c.lineWidth = 5 line from draw function to not to override change. Perhaps do c.lineWidth = 5 in a initializer function ot smt as a default value.
thanks you all for help but i solved it just saved the value in variable and manipulate it like #Whatatimetobealive said

Why the coordinates of mouse in canvas are wrong?

I intend to draw free with the mouse cursor in canvas. My code seems to do the part with color but it doesn't take the exact coordinates of my current mouse position in canvas when i draw.
<body>
<canvas id="canvas" style=" width: 400; height: 400px; background-color:yellow; position: absolute; margin-left:100px; margin-top:30px"></canvas>
<script>
var Color = 'blue';
var Canvas = document.getElementById('canvas');
var Context = Canvas.getContext('2d');
$("canvas").on("mousemove",function(e){
X = e.clientX - canvas.offsetLeft;
Y = e.clientY - canvas.offsetTop;
Context.strokeStyle = Color;
Context.lineWidth = 3;
Context.lineCap = 'round';
Context.beginPath();
Context.moveTo(X,Y);
Context.lineTo(X,Y);
Context.fillRect(X,Y, 3,3)
Context.stroke();
Context.closePath();
});
</script>
</body>
https://jsfiddle.net/93L8mLnf/
I tested in console.log the coordinates and they are corect. I'm confused..
You need to synchronize the dimension of the canvas with the DOM element.
Add this:
Canvas.width = Canvas.clientWidth;
Canvas.height = Canvas.clientHeight;
Demonstration
You'll also notice the canvas isn't blurred anymore.
Note that this must be done every time the canvas DOM element changes size (usually because the window is resized) so when your element isn't of fixed size you should bind an event handler on the window resize event to do that synchronization again (and usually to redraw the content).
You have to add width and height by canvas attributes
see in fiddle
<canvas id="canvas" style="background-color:yellow;" width="250" height="250"></canvas>

How to move canvas elements?

How to move first element with black fill to mouse cursor? Or just how to move it to my position in event handler?
Javascript:
var drawing = document.getElementById('canvas');
var ctx = drawing.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(188, 50, 200, 100);
ctx.fillStyle = 'yellow';
ctx.fillRect(0, 0, 200, 100);
document.onmousemove = function(e) {
/* How to move rectangle here? */
}
http://jsfiddle.net/9545qbo4/1/
Thanks in advance.
I think it is not possible on canvas, but your function can do it like this:
ctx.clearRect(/* Old rect position */);
ctx.fillRect(/* New rect position*/);
EDIT: The same question is here.

Image is flickering continuously in pressing button?

The Image is flickering as I continuously push the button. The problem might be in ctx.clearRect(0,0,100,500) . How can I resolve the problem?
I am trying to animate in HTML 5 canvas.
I need a moving object in canvas and when I push the button, the other moving object follow the previous without flickering.
function draw(x,y){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0,100,500); // This may be the problem
var img=document.getElementById("Image");
ctx.drawImage(img,50,y);
ctx.restore();
y -= 10;
var loopTimer = setTimeout('draw('+x+','+y+')',50);
}
HTML 5
<button onclick="draw(0,500)">Draw</button>
<canvas id="canvas" width="600" height="500">
</canvas>
It looks like the problem may be because you aren't clearing the entire canvas. Try this:
function draw(x,y){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0, canvas.width, canvas.height);
var img=document.getElementById("Image");
ctx.drawImage(img,50,y);
ctx.restore();
y -= 10;
var loopTimer = setTimeout('draw('+x+','+y+')',50);
}
Demo
The image flicker when you press the button more than once, which means you start the setTimeout() more than once. Add a variable to check if it's already been pressed.

Categories

Resources