javascript,canvas,rotation,geometry , rotating a square in javascript

## Question:

Tag: javascript,canvas,rotation,geometry

I am trying to rotate a square about its center in javascript. Although in this case I am using canvas to draw the square, I need to have a functional method of rotating the square for use elsewhere so just rotating the canvas is not acceptable. This is what I have so far

var thecanvas = this.myCanvas;

var canvaswidth = thecanvas.width;
tlx = (0 - ((canvaswidth * 0.6) / 2));
tly = (0 - ((canvaswidth * 0.6) / 2));
trx = (0 + ((canvaswidth * 0.6) / 2));
tryy = (0 - ((canvaswidth * 0.6) / 2));
blx = (0 - ((canvaswidth * 0.6) / 2));
bly = (0 + ((canvaswidth * 0.6) / 2));
brx = (0 + ((canvaswidth * 0.6) / 2));
bry = (0 + ((canvaswidth * 0.6) / 2));

tlx = (((tlx) * (this._cosD(orientation))) - ((tly) * (this._sinD(orientation))));
tly = ((tlx) * (this._sinD(orientation)) + (tly) * (this._cosD(orientation)));
trx = (((trx) * (this._cosD(orientation))) - ((tryy) * (this._sinD(orientation))));
tryy = ((trx) * (this._sinD(orientation)) + (tryy) * (this._cosD(orientation)));
blx = ((blx) * (this._cosD(orientation)) - (bly) * (this._sinD(orientation)));
bly = ((blx) * (this._sinD(orientation)) + (bly) * (this._cosD(orientation)));
brx = ((brx) * (this._cosD(orientation)) - (bry) * (this._sinD(orientation)));
bry = ((brx) * (this._sinD(orientation)) + (bry) * (this._cosD(orientation)));

tlx = (tlx + (canvaswidth / 2));
tly = (tly + (canvaswidth / 2));
trx = (trx + (canvaswidth / 2));
tryy = (tryy + (canvaswidth / 2));
blx = (blx + (canvaswidth / 2));
bly = (bly + (canvaswidth / 2));
brx = (brx + (canvaswidth / 2));
bry = (bry + (canvaswidth / 2));

var c2 = thecanvas.getContext('2d');
c2.fillStyle = '#f00';
c2.beginPath();
c2.moveTo(tlx, tly);
c2.lineTo(trx, tryy);
c2.lineTo(brx, bry);
c2.lineTo(blx, bly);
c2.closePath();
c2.fill();`

orientation is a value from -90-90 in degrees. This code starts to rotate the square but the square continues to "squish" until it is completely gone by 90 degrees. Obviously my formula for rotation is thrown off somewhere but I cant figure out how.

You could manually implement a transformation matrix. This allows you to set up the matrix for both read and write, then apply it to the points returning absolute points with the new actual values without the need or hassle to make special code for each use-case.

The formula for the (2D affine) using a 3x3 matrix would be:

or simplified in JavaScript:

var newX = x * a + y * c + e,    // e (or tx) x 1 => e
newY = x * b + y * d + f;    // f (or ty) x 1 => f

Now you would need to multiply the matrix with another to add rotation, translation, scale etc. The common way of doing this is this way - assume we have an object holding our values, you could do:

function Matrix() {
this.a = 1;  // 1,0,0,1,0,0 = identity matrix (untransformed)
this.b = 0;
this.c = 0;
this.d = 1;
this.e = 0;
this.f = 0;
}

Matrix.prototype = {

// we need to be able to multiply matrices to accumulate values:
transform: function(a2, b2, c2, d2, e2, f2) {

var a1 = this.a,
b1 = this.b,
c1 = this.c,
d1 = this.d,
e1 = this.e,
f1 = this.f;

/* matrix order (canvas compatible):
* ace
* bdf
* 001
*/
this.a = a1 * a2 + c1 * b2;
this.b = b1 * a2 + d1 * b2;
this.c = a1 * c2 + c1 * d2;
this.d = b1 * c2 + d1 * d2;
this.e = a1 * e2 + c1 * f2 + e1;
this.f = b1 * e2 + d1 * f2 + f1;
}
}

With the core set up you can now add methods to do for example rotation:

rotate: function(angle) {
var cos = Math.cos(angle),
sin = Math.sin(angle);
this.transform(cos, sin, -sin, cos, 0, 0);
}

scale:

scale: function(sx, sy) {
this.transform(sx, 0, 0, sy, 0, 0);
}

translate:

translate: function(tx, ty) {
this.transform(1, 0, 0, 1, tx, ty);
}

and so forth depending on your needs. Note that these will accumulate as with the ordinary canvas/SVG matrix. Reset to identity to remove all transforms.

All you need to do now is to feed your points after settings transformation to get the absolute points - lets say we have a box of 100x100 we want to rotate at center:

applyToPoint: function(p) {
return {
x: p.x * this.a + p.y * this.c + this.e,
y: p.x * this.b + p.y * this.d + this.f
}
}

will allow us to do:

var m = new Matrix();
m.translate(50, 50);
m.rotate(0.3);
m.translate(-50, 50);

var points = [
{x: 0, y: 0},      // upper-left
{x: 100, y: 0},    // upper-right
{x: 100, y: 100},  // bottom-right
{x: 0, y: 100}     // bottom-left
],
result = [],
i = 0, p;

// transform points
while(p = points[i++]) result.push(m.applyToPoint(p));

# Demo

Red box is original coordinates, blue is the transformed points which we now have access to:

function Matrix() {
this.a = 1; // identity matrix
this.b = 0;
this.c = 0;
this.d = 1;
this.e = 0;
this.f = 0;
}

Matrix.prototype = {

applyToPoint: function(p) {
return {
x: p.x * this.a + p.y * this.c + this.e,
y: p.x * this.b + p.y * this.d + this.f
}
},

transform: function(a2, b2, c2, d2, e2, f2) {

var a1 = this.a,
b1 = this.b,
c1 = this.c,
d1 = this.d,
e1 = this.e,
f1 = this.f;

/* matrix order (canvas compatible):
* ace
* bdf
* 001
*/
this.a = a1 * a2 + c1 * b2;
this.b = b1 * a2 + d1 * b2;
this.c = a1 * c2 + c1 * d2;
this.d = b1 * c2 + d1 * d2;
this.e = a1 * e2 + c1 * f2 + e1;
this.f = b1 * e2 + d1 * f2 + f1;
},

rotate: function(angle) {
var cos = Math.cos(angle),
sin = Math.sin(angle);
this.transform(cos, sin, -sin, cos, 0, 0);
},

scale: function(sx, sy) {
this.transform(sx, 0, 0, sy, 0, 0);
},

translate: function(tx, ty) {
this.transform(1, 0, 0, 1, tx, ty);
}
};

// apply some transformation:
var m = new Matrix();     // our manual transformation-matrix
m.translate(50, 50);      // center of box
m.rotate(0.3);            // some angle in radians
m.translate(-50, -50);    // translate back

var points = [
{x: 0, y: 0},       // upper-left
{x: 100, y: 0},     // upper-right
{x: 100, y: 100},   // bottom-right
{x: 0, y: 100}      // bottom-left
],
result = [], i = 0, p;

// transform points
while(p = points[i++]) result.push(m.applyToPoint(p));

// draw boxes to canvas:
var ctx = document.querySelector("canvas").getContext("2d");
ctx.translate(30, 30);    // give some room for rotation for this demo

drawPolygon(points, "red");
drawPolygon(result, "blue");

drawCoord(points[0]);     // plot old point
drawCoord(result[0]);     // plot resulting point

// Compare using ordinary canvas: -------------------

ctx.translate(150, 0);     // give some space
ctx.fillText("Regular canvas:", 0, -20);

drawPolygon(points, "red");

ctx.translate(50, 50);      // center of box
ctx.rotate(0.3);            // some angle in radians
ctx.translate(-50, -50);    // translate back

drawPolygon(points, "blue");

// plot result:
function drawPolygon(pts, color) {
ctx.beginPath();
ctx.strokeStyle = color;
ctx.moveTo(pts[0].x, pts[0].y);
for(var i = 1, p; p = pts[i++];) ctx.lineTo(p.x, p.y);
ctx.closePath();
ctx.stroke();
}

function drawCoord(p) {
ctx.fillStyle = "#0c0"; ctx.fillRect(p.x - 2, p.y - 2, 4, 4);
ctx.fillStyle = "#000";
ctx.fillText(p.x.toFixed(1) + "," + p.y.toFixed(1), p.x, p.y - 2);
}
<canvas><canvas>

If you don't want to implement this yourselves, or want a more extensive solution, feel free to check out my (free) matrix solution here.

The future will give us currentTransform on the context (currently only available in Chrome, Firefox struggles with a bug) returning a SVGMatrix object which you can use in pretty much the same way as the above implementation.

# Related:

## Onclick add html content and remove it by clicking “delete” link

javascript,jquery
I have some issue, help me please to find where is the mistake. \$(document).ready(function(){ \$(function() { var scntDiv = \$('#p_scents'); var i = \$('#p_scents .row-wrap').size() + 1; \$('body').on('click', '.add-item', function() { \$('<div class="row-wrap cf"><div class="col-md-3 col-sm-3 col-xs-12"><input type="text" placeholder="Наименование" name="item_name' + i +'"></div><div class="col-md-2 col-sm-2 col-xs-12"><input type="text" placeholder="Количество" name="item_count' +...

## Javascript function to validate contents of an array

javascript,arrays
Here's what is asked: validItems(items) – this function receives a string array of items which are to be for a customer. The function returns an empty string indicating all item codes in the array are valid; otherwise the function returns the first invalid item code in the array. All item...

## Saving data using promises

javascript,parse.com,promise
On Parse.com I have the following function, and my question follows: function myFunction(array, value) { var logMessage; logMessage = "array: " + array.length.toString(); console.log(logMessage); if (!array.length) return; if (!value) value = Math.min(10, array.length); if (array[array.length - 1].get("advertisePointNumber") >= value) return; var classPromise; array[array.length - 1].set("advertisePointNumber", value); logMessage = "(BIS)array: "...

## Aligning StackPanel to top-center in Canvas

c#,wpf,xaml,canvas
I'm trying to create an application which is supposed to measure quick reaction performance of it's user. The application starts up in full-screen mode and resizes it's elements accordingly to the screen resolution. The project was strongly inspired by training_aim_csgo2 map. It's mostly done, but here is the problem: I...

## show div only when printing

javascript,html,css
Let's say that I have <div id="printOnly"> <b>Title</b> <p> Printing content </p> </div> Is it possible to hide this div when page rendering and to show only when printing this div?...

## Changing interval time to random?

javascript
Im looking for a way to change the way my javascript number counter is working. Now it just counts up every second but I want it to count at random times between 1 second and 15 seconds. function startCount(){ timer = setInterval (count, 1000); } function count(){ var el =...

Here is a sample google map with three polygons. I am setting the infowindow for each polygon as, for (var i in coordinates) { arr = []; for (var j=0; j < coordinates[i].length; j++) { arr.push( new google.maps.LatLng( parseFloat(coordinates[i][j][0]), parseFloat(coordinates[i][j][1]) )); bounds.extend(arr[arr.length-1]) } // Construct the polygon. polygons.push(new google.maps.Polygon({ paths:...

## Teechart HTML5, line color and thickness

javascript,html5,teechart
How do you change the line color and thickness of a series in Teechart HTML5. I have been looking through the examples, but i can't find anything describing that....

## Not able to access variables in required file

javascript,gulp,require,browserify
I'm using browserify on a project and am running in to the following: I have a file test.js. In test.js there is nothing but the following: var test = 'test'; Now, in the same directory I have my main file 'app.js'. I require test.js and try to access the 'test'...

## How to send current page number in Ajax request

javascript,jquery,ajax,spring-mvc,datatables
I am using jQuery DataTable to display huge amount of data in a table. I am getting data page wise on Ajax request like this: var pageNo = 1; \$('#propertyTable').dataTable( { "processing": true, "serverSide": true, "ajax": "\${contextPath}/admin/getNextPageData/"+pageNo+"/"+10, "columns": [ { "data": "propertyId" }, { "data": "propertyname" }, { "data": "propertyType"...

## How to find the days b/w two long date values

javascript,jquery,date
I have two long dates value. For Ex: 1433097000000 1434479400000 Here i have to find the days between these two by jquery For Ex: 15/06/2015 - 22/06/2015 If it is more than 5 days, I want to get from is 15/06/2016, to is 19/06/2015. It is based on long values...

## want to show and hide text using “this” jquery

javascript,jquery
I want to achieve this effect with this because I have several paragraphs like this so I don't wanna use id for each paragraph <p class="desc_services_subheading"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,...

## Dynamically resize side-by-side images with different dimensions to the same height

javascript,html,css,image
I have two images side-by-side within a block-level container with arbitrarily different dimensions (as in, they could be any two images) that I want to dynamically adjust the width of so that the overall height of the two images is the same. I don't think this can be done in...

## Cant submit form

javascript,php
Basically I've got a form with 5 radio buttons. No submit button. I want the form to run when the user clicks on any of the radio buttons, so this is what I did. <input id="5" type="radio" name="star" onchange="this.form.submit();" <?php if (\$row["star"] =="5") echo "checked";?> value="5"/> a querystring is required...

## Error: [\$injector:unpr] Unknown provider: RestangularProvider <- Restangular <- ctrlAG

javascript,angularjs,restangular
I have one app: app.js: angular.module('AngApp', [ 'angularGrid' ]); My own restangular service.js: var app = angular.module('AngApp'); app.factory('restService', ['Restangular', function (Restangular) { // make use of Restangular } ]); and controller.js: var app = angular.module('AngApp'); app.controller('ctrlAG', ['\$scope', '\$http', '\$log', '\$mdDialog', 'Restangular',function (\$scope,\$http, \$log, \$mdDialog, Restangular) { // make use of...

javascript
When I Open Login and signUp Portal it open with the both tab contents and then when I click on Login tab it open login tab content and on click register tab it open register tab page. But again after refresh the page popup showing both tabs content together![enter image...

## Wordpress log out using URL and redirect to specify page

javascript,php,wordpress
I have one Wordpress installation . i need to log out the user without any indication user is coming from particular URL.Is it possible? My code: <?php if(\$_GET['logout'] == 1) { \$redirect_to = current_page_url(); ?> <script> window.location.href="<?php echo wp_logout_url( \$redirect_to ); ?>"; </script> <?php } ?> I am using above...

## How to use a service with Http request in Angular JS

javascript,angularjs
I'm using AngularJS to build my web application, I've been always using controllers to make HTTP request, which makes things easier and clear for me. But for a better code structure, and better execution for my application, I wanted to use services instead of controllers to use the web service....

## Parsing XML array using Jquery

javascript,jquery,xml,jquery-mobile
I have stuck up with an issue of passing XML using Jquery. I am getting empty array while traversing to jquery.Please help me how to get datas from XML array. I have mentioned my code below. XML <?xml version="1.0" encoding="UTF-8"?> <json> <json> <CustomerName>999GIZA MID INSURANCEAND SERVICES PVT LTD</CustomerName> <mobiLastReceiptDate>null</mobiLastReceiptDate> </json>...

## slideToggle state not working with multiple boxes

I'm trying to save the toggle state of collapsable boxes using cookies. Here's my code: HTML: <div class="box_container"> <div class="box_handle"> Title </div> <div class="box" data-title="admin_actions"> Content </div> </div> Javascript: \$('div.box_container div.box_handle').click(function() { \$(this).next('.box').slideToggle('fast'); }); \$.each(\$('div.box_container div.box_handle'), function(index,value){ if (\$.cookie('show_box_' + \$(value).next('.box').attr('data-title')) != 'closed'){...

## Merge and sum values and put them in an array

javascript,arrays,angularjs,foreach
I'm retrieving values from an external source and apply a foreach loop to the results, with the code below. angular.forEach(data, function(value, key) { if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) { console.log(value.firstname + ' - ' + value.distance); } else { //do nothing } }); The result is console...

## show/hide an overflow div on anchor

javascript,jquery,html,scroll
I'm trying to make a div appear (if not already visible) and be scrolled to a specific anchor. I found this answer and try to use it but it looks like it doesn't work well... http://stackoverflow.com/a/7513110/3703099 My code : http://jsfiddle.net/0sq2rfcx/9/ As you can see, when you click on button it...

## Javascript: Forloop Difference between i++ and (i+1)

javascript,loops,for-loop
I was building a javascript for loop and I want to compare the value of an array to the next value in the array. If both values are not equal, I want to return true, otherwise I want to return false. In the code below I pass the string "aba",...

## Click on link next link should be display on same page

javascript,php,jquery,html,css3
I have a single page website and need to link the navigation to IDs in the page. I have three links: "About us", "Our Project", "contact". So if user clicks on "About ", the About section will be displayed, same with other links. Inside Our project there is Two buttons...

## Background-image style with JS not working in ie9

javascript,jquery,html,internet-explorer
I'm working on a site and im having some issues with my slider in IE9. What I've done is that I've made a div that gets the background image changed every few seconds depending on the img tags within. You can see it in function here: http://diakondk.quine.pil.dk/ It works wonders...

## why i don't get return value javascript

javascript,jquery,html,json,html5
When i debug my code i can see i have value but i don't get value to createCheckBoxPlatform FN function createCheckBoxPlatform(data) { var platform = ""; \$.each(data, function (i, item) { platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>' +...

javascript,knockout.js,requirejs,knockout-components
Context I have been fiddling around and trying to create my own (just another) SPA framework. In this framework I've been trying to create a custom component loader to be able to do some dependency injection 'n stuff on the viewModels I'm loading. Used KnockoutJS version: 3.3.0 Problem The loadViewModel...

## Get elements containing text from array

javascript,jquery,html,arrays,contains
I want to search all the elements containing any string in the array. For example I have following list of items <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li> <li>hockey stick</li> </ul> and this array var arr = ['bat', 'ball']; It should select all the elements having text bat and ball....

## Create array from another with specific indices

javascript,arrays
I have two arrays, one of data and one of indices: var data = [ 'h', 'e', 'l', 'l', 'o', ' ' ]; var indices = [ 4, 0, 5, 0, 1, 2, 2 ]; I would like to create a third array, using cells of data in order indicated...

## JSLint error: “Expected a newline at EOF”, conflict with Beautify plugin

javascript,gruntjs,jslint,beautify
I have a problem while building the sources using Grunt, with JSLint task for error check: L177: Expected a newline at the end of the file. Warning: Formatting check failed. Use --force to continue. Aborted due to warnings. The problem is obvious, but I use also the Beautify plugin for...

## Javascript change the souce of all images present inside a string

javascript,jquery
I have a message or string which contain both text as well as images as below. var text = '<span class="user_message">hiiiiiii <img title=":benztip" src="path../files/stickers/1427956613.gif"> <img src="path../files/stickers/416397278.gif" title=":happy"></span>'; Before appending this to the the chat div i want to replace the src of the images to a default image. How can...

## Please can someone help me understand the exec method for regular expressions?

javascript,regex
The best place I have found for the exec method is Eloquent Javascript Chapter 9: "Regular expressions also have an exec (execute) method that will return null if no match was found and return an object with information about the match otherwise. An object returned from exec has an index...

## Replacing elements in an HTML file with JSON objects

javascript,json,replace
I am writing some Javascript to: Read in and Parse a JSON file Read in an HTML file (created as a template file) Replace elements in the HTML file with elements from the JSON file. It is only replacing the first element obj.verb. Can someone please help me figure out...

## Insert data in collection at Meteor's startup

javascript,json,meteor,data,startup
I would like to insert data at Meteor's startup. (And after from a JSON file) At startup, I create a new account and I would like to insert data and link it to this account once this one created. This is the code that creates the new account at startup:...

## How To Check Value Of String

javascript,css,string,numeric
<span id='amount'>0.00000000</span> <a class='button-withdraw' id='tombolco' href='#'>Checkout</a> <script> var amount = document.getElementById("amount").innerHTML; if (amount >= 0.001) { document.GetElementById("tombolco").style = "display:block"; } else { document.GetElementById("tombolco").style = "display:none"; } </script> Why my code doesn't work? What's wrong with it and how to solve it?...

## Angular \$http and Fusion Tables in IE9

I am trying a simple get request to a google fusion table in my angular controller. \$http.get(url) .success(function(data) { //Do stuff with data }) This works in firefox, chrome, safari and IE10+ however in IE9 (Which I am requried to support) the request fails to even send and the console...

## Converting “i+=n” for-loop to \$.each

javascript,jquery
I have the below html structure: <div class="thumbnail"></div> <div class="thumbnail"></div> <div class="thumbnail"></div> <div class="thumbnail"></div> <div class="thumbnail"></div> <div class="thumbnail"></div> <div class="thumbnail"></div> <div class="thumbnail"></div> Now to group/wrap each 4 items in a separate div I did as below: var div=\$('.thumbnail'); for(var i = 0; i < div.length; i+=4) { div.slice(i, i+4).wrapAll("<div...

javascript,html

## Javascript sort array of objects in reverse chronological order

javascript,arrays,sorting
I have an array of objects which holds a list of jobs and I would like to sort them in reverse chronological order as they would appear on a resume for example. I came up with the below solution which 'seems' to work but I was wondering if there is...

## Can't call fetch directly in Backbone model listenTo

javascript,backbone.js,coffeescript
I'm trying to have a model listen to a collection and fetch itself when the collection changes: class Team extends Backbone.Model urlRoot: '/team', initialize: function(attributes, options) { this.listenTo(members, 'change', this.fetch) The fetch does seem to trigger, but the url is all messed up, and to get it to work I...

## session value in javascript cannot be set

javascript,function,session
I am quite new to javascript, I wonder why my session value in javascript wont be set to 1 even I tried. When call this function again, the value of the session will change again. My javascript code as below. <script type="text/javascript"> function Confirm() { alert(<%=Session["Once"]%> != 1); var value...

## How to get my node.js mocha test running?

javascript,node.js,mocha,supertest
I have developed a service in node.js and looking to create my first ever mocha test for this in a seperate file test.js, so I can run the test like this: mocha test I could not figure out how to get the reference to my app, routes.js: var _ =...

## Javscript Replace Text in tags without changing children element HTML and Content

javascript,jquery
I have a script where I'd like to replace the text anywhere in the body visible to the user like so: \$("body").html(\$("body").html().replace(/replaced word/g,'HELLO')); This works but it works to well. Whenever "replaced word" is within a tag, like a href, or span, or div, or anything it throws off all...

## Saving image to localstorage - canvas

javascript,html5,html5-canvas
I'm using html5 storage to store my image. It works great in chrome. In FireFox it works 8/10 times. function getBase64Image(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); console.log("line 1 : " + img.src); var dataURL = canvas.toDataURL('image/jpeg'); console.log("line...

## Substring of a file

javascript,arrays,substring
I have a file that is structure like this : var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d"; Now I would extract all letters "c" and "d" of this file and put those letter in array, structure like this: var array = [ [a,b,1], [a,b,2], [a,b,3], [a,b,4], [a,b,5] ]; How...

## Automatically calling server side class without

javascript,html,ajax
I have an anchor which calls a server side class when clicked, but I want to modify it so that the class is called as soon as the page loads, without having to click an anchor. <a href="#" class="_repLikeMore" data-id="1234" data-type="pid" data-app="forums"> ...

## Target next instance of an element/div

javascript,jquery,html
I have the following HTML structure and JavaScript file: .html <li> <button class="show-more"></button> some more elements <div class="hidden"></div> </li> JavaScript \$( ".show-more" ).click(function() { event.preventDefault(); \$( this ).next().slideToggle( "fast", function() { }); }); I need the click event to toggle the next first instance of .hidden, however the click event...

## Sockets make no sense?

javascript,node.js,sockets
I'm using the 'ws' library for Node.js. I can write code that sends data from my server to my client, posting a date and time update, and closes the socket when I click a button; var wss = new WebSocketServer({server: server}); console.log("WebSocket server created"); wss.on('connection', function(socket) { // SEND DATE...