How to rotate the existing content of HTML5 canvas? - javascript

Is there a way to rotate the existing content of HTML5 canvas by Javascript? I know it's possible to rotate an image that will be drawn on to canvas, but I want to rotate the content that has been drawn on to canvas, for example, a 200x200 corner of a 400x400 canvas, or any specific region of an existing canvas.
Same question to scale the existing canvas content...
I know getImageData/putImageData provide a potential to transform the pixel array, but it's just too slow and inefficient.

It's pretty easy to do with a temp canvas.
Live Demo
Live Demo Animated (just for the heck of it)
The above example draws 2 boxes, then rotates and scales from 0,0 to 200,200
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = canvas.height = 400;
// fill the canvas black, and draw 2 boxes
ctx.fillStyle = "#000";
ctx.fillRect(0,0,400,400);
ctx.fillStyle = "rgb(255,0,0)";
ctx.fillRect(10,10,190,190);
ctx.fillStyle = "rgb(255,255,0)";
ctx.fillRect(250,250,90,90);
// Create a temp canvas to store our data (because we need to clear the other box after rotation.
var tempCanvas = document.createElement("canvas"),
tempCtx = tempCanvas.getContext("2d");
tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
// put our data onto the temp canvas
tempCtx.drawImage(canvas,0,0,canvas.width,canvas.height);
// Append for debugging purposes, just to show what the canvas did look like before the transforms.
document.body.appendChild(tempCanvas);
// Now clear the portion to rotate.
ctx.fillStyle = "#000";
ctx.fillRect(0,0,200,200);
ctx.save();
// Translate (190/2 is half of the box we drew)
ctx.translate(190/2, 0);
// Scale
ctx.scale(0.5,0.5);
// Rotate it
ctx.rotate(45*Math.PI/180);
// Finally draw the image data from the temp canvas.
ctx.drawImage(tempCanvas,0,0,200,200,10,10,190,190);
ctx.restore();

If you first want to draw on a canvas and then rotate it for use on e.g. corners, you can to that when you "clone" the canvas or by using CSS.
Examples
Get the first canvas element:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
draw on it:
ctx.fillStyle = 'blue';
ctx.fillRect(0,0, 25, 5);
ctx.fill();
ctx.fillStyle = 'red';
ctx.fillRect(25, 0, 25, 5);
ctx.fill();
clone it to another canvas (that is rotated by CSS):
var ctx2 = document.getElementById("canvas2").getContext("2d");
ctx2.drawImage(canvas, 0,0);
or rotate the canvas while you "clone" it:
var ctx3 = document.getElementById("canvas3").getContext("2d");
ctx3.rotate(Math.PI/2);
ctx3.translate(0,-50);
ctx3.drawImage(canvas, 0,0);
here is the CSS for rotating it:
#canvas2 {
-webkit-transform:rotate(90deg);
-moz-transform:rotate(90deg);
-o-transform:rotate(90deg);
-ms-transform:rotate(90deg);
}
Here is the full example:
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = 'blue';
ctx.fillRect(0,0, 25, 5);
ctx.fill();
ctx.fillStyle = 'red';
ctx.fillRect(25, 0, 25, 5);
ctx.fill();
var ctx2 = document.getElementById("canvas2").getContext("2d");
ctx2.drawImage(canvas, 0,0);
var ctx3 = document.getElementById("canvas3").getContext("2d");
ctx3.rotate(Math.PI/2);
ctx3.translate(0,-50);
ctx3.drawImage(canvas, 0,0);
}
</script>
<style>
#canvas2 {
-webkit-transform:rotate(90deg);
-moz-transform:rotate(90deg);
-o-transform:rotate(90deg);
-ms-transform:rotate(90deg);
}
</style>
</head>
<body>
<canvas id="canvas" width="50" height="50"></canvas>
<canvas id="canvas2" width="50" height="50"></canvas>
<canvas id="canvas3" width="50" height="50"></canvas>
</body>
</html>

Related

Rotate a shape as array of points on its origins

I have a web app that receives some array of points and I need to draw them on a canvas. Unfortunately, I get the dataset not the way I want. I need to rotate the shapes 180 degrees. I have no idea how to do this...
Please see the example in the snippet.
// Main template shape
let shape = [{x: 10, y:10}, {x: 120, y:10}, {x: 110, y:110}, {x: 50, y:175}];
let canvas = {}; // Canvas to draw on
let ctx = {}; // Context of the Canvas
// Init elements
$( document ).ready(function() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
drawShape();
});
// Draw the template
function drawShape() {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = 'yellow';
ctx.fillStyle = 'red';
for(let point of shape) {
ctx.lineTo(point.x, point.y);
}
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Hahaha!</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;"></canvas>
</body>
</html>
If I understand your question correctly, you want to turn the shape around by 180 degrees ?
As in vertically invert it ? If this is it, here's a solution, you need an axis relative to which to turn it. Problem is if you just invert for every point (x,y), you put (x,-y), canvas being defined for only positive values it won't show on your screen, imagine it outstide the screen, you need to "push" it back down onto the canvas, you do this by adding the height of the canvas after having inverted the shape.
// Main template shape
let shape = [ {x:10, y:10}, {x:120, y:10}, {x:110, y:110}, {x:50, y:175} ];
let canvas = {}; // Canvas to draw on
let ctx = {}; // Context of the Canvas
// Init elements
$( document ).ready(function() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
drawShape();
});
// Draw the template
function drawShape() {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = 'yellow';
ctx.fillStyle = 'red';
for(let i = 0; i < shape.length; i++) {
ctx.lineTo(shape[i][0], -shape[i][1] + 200);
}
for(let point of shape) {
ctx.lineTo(point.x, -point.y + 200);
}
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Hahaha!</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;"></canvas>
</body>
</html>

Adding Image within a canvas circle

I am learning drawing canvas and now I have task. I need to add an image within the inner circle. The image position needs to be inside the circle. Also I attached the image with this post. My code are:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0,0,200,100);
var cicleT = document.getElementById("myCanvas");
var dtx = cicleT.getContext("2d");
dtx.arc(95,50,40,0,2*Math.PI);
dtx.stroke();
dtx.fillStyle = "red";
dtx.fill();
dtx.fillStyle = "black"; // font color to write the text with
var font = "bold 13px serif";
dtx.font = font;
dtx.textBaseline = "bottom";
dtx.fillText("Bangladesh",50,50, 95 ,25);
</script>
</body>
</html>
You can use ctx.clip to cut out the region you want to draw, and the following operation will be refined on the region, remember to restore when you complete the works that needs to be refined.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 200, 100);
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
ctx.fillStyle = "red";
ctx.fill();
// For safety, I move the draw image and draw text to image.onload.
var image = document.createElement('img');
image.onload = function() {
var iw = image.width;
var ih = image.height;
var r = Math.sqrt(Math.pow(iw/2, 2) + Math.pow(ih/2, 2));
var ratio = 40 / r;
var tw = iw * ratio;
var th = ih * ratio;
// Use the same ctx is ok.
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
// Save the current state of context, which is not clipped yet.
ctx.save();
// Clip by the stroke.
ctx.clip();
// Draw image.
//
ctx.drawImage(image, 0, 0, iw, ih, 95 - tw/2, 50 - th/2, tw, th);
// Restore the context, otherwise the text will also be clipped.
ctx.restore();
ctx.fillStyle = "black"; // font color to write the text with
var font = "bold 13px serif";
ctx.font = font;
ctx.textBaseline = "bottom";
ctx.fillText("Bangladesh", 50, 50, 95, 25);
};
image.src = "https://i.stack.imgur.com/jy3YL.jpg";
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

Clip canvas strokes to image

I'm trying to animate a pen filling in a variable width shape, currently working with html5 canvas. Ideally, I want to be able to have the sample below both start light and get colored in dark, as well as not appear at all and get colored in as though being drawn from nothing.
source-in doesn't seem to work, at least in firefox.
The image in question is a simple-ish SVG path, so if there's a reasonable way to generate canvas clip paths from SVG bezier paths, that would work as well.
var img = new Image();
img.src = "data:image/svg+xml;base64,...";
var xRecords = [...];
var yRecords = [...];
var canvas = document.getElementById("topCanvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
ctx.strokeStyle = "#0000ff";
ctx.lineWidth = 90;
ctx.beginPath();
ctx.lineCap = "round";
ctx.moveTo(xRecords[0], yRecords[0]);
for(var i = 0; i < xRecords.length; i++) {
ctx.lineTo(xRecords[i], yRecords[i]);
ctx.stroke();
}
http://codepen.io/matelich/pen/gpLmOW
Generating alternate versions of the image is not a big deal if that would help. Oh and the animation is just a sample.
Update This works for the most part on Chrome and IE, but not on Firefox: http://codepen.io/matelich/pen/pJNeRq
FF doesn't like your SVG dataURL.
Option#1:
You could use a .png image instead.
Option#2:
You can create a cubic Bezier curve (like SVG's "C") in canvas using context.moveTo and context.bezierCurveTo.
Then your compositing will work fine even in FF:
var canvas = document.getElementById("topCanvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload=start;
img.src = 'https://dl.dropboxusercontent.com/u/139992952/multple/svg2png.png';
var xRecords = [117.6970666666671, 137.5037866666671, 139.6247579166671, 138.2627966666671, 134.75555041666712, 130.4406666666671, 126.65579291666711, 124.7385766666671, 126.0266654166671, 131.8577066666671, 155.5330366666671, 191.76562666666712, 224.94953666666714, 239.47882666666712];
var yRecords = [143.95648000000128, 200.21077333333463, 232.21213000000128, 264.735546666668, 296.24260333333467, 325.19488000000126, 350.05395666666794, 369.2814133333347, 381.33883000000134, 384.687786666668, 371.9640133333346, 346.7872000000013, 322.15182666666794, 311.05237333333463];
function start(){
canvas.width=img.width;
canvas.height=img.height;
ctx.beginPath();
ctx.rect(0, 0, 640, 640);
ctx.fillStyle = 'white';
ctx.fill();
ctx.globalCompositeOperation = "darker";
ctx.drawImage(img, 0, 0);
ctx.globalCompositeOperation = "lighter";
ctx.drawImage(img, 0, 0);
ctx.globalCompositeOperation = "xor";
ctx.drawImage(img, 0, 0);
ctx.globalCompositeOperation = "destination-over";
ctx.strokeStyle = "#0000ff";
ctx.lineWidth = 90;
ctx.beginPath();
ctx.lineCap = "round";
ctx.moveTo(xRecords[0], yRecords[0]);
var i = 0;
function drawNext()
{
i++;
console.log(i+"!");
if(i >= xRecords.length) { return; }
ctx.lineTo(xRecords[i], yRecords[i]);
ctx.stroke();
setTimeout(drawNext, 500);
}
drawNext();
}
body{ background-color: white; }
#canvas{border:1px solid red;}
<canvas id="topCanvas" width=300 height=300></canvas>

Draw Shape in JQuery

I am working in Jquery.
I have 4 Cordinates , Width, Height, x Position and Y position.
How can i create a Square shape Using This
$('#box').drawRect(20,20,2,30,{color:'red'})
I tried this and Not Working. Looking for a Good Hand
Here is My Demo. http://fiddle.jshell.net/vbm2vhu4/
try using canvas tag in JavaScript..
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.rect(20, 20, 150, 100);
ctx.stroke();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
JSFIDDLE
JAVASCRIPT
Draw a circle
$(document).ready(function(){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.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 = '#003300';
context.stroke();
});
Drawing a rectangle requires canvas. You really do not need to use jquery for it. It can be well done with Javascript. I am attaching my example here.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150">
Browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Blue rectangle
ctx.beginPath();
ctx.lineWidth = "10";
ctx.strokeStyle = "blue";
ctx.rect(50, 50, 50, 50);
ctx.stroke();
</script>
</body>
</html>
Paste this into a notepad and save as .html and load it in your browser
or jsfiddle http://jsfiddle.net/ssbiswal1987/vsbak0mq/

Moving Objects on html5 Canvas

I placed an text on html5 canvas object using fillText option, question is I need to move the text position or change the color of the text that is already rendered.
Shortly I need to know how to Manipulate particular child of canvas element
This will move a small circle over your canvas
var can = document.getElementById('canvas');
can.height = 1000; can.width = 1300;
var ctx = can.getContext('2d');
var x = 10, y = 100;
ctx.fillStyle = "black";
ctx.fillRect(700, 100, 100, 100);
function draw() {
ctx.beginPath();
ctx.arc(x, y, 20, 0, 2 * Math.PI);
ctx.fillStyle = 'rgba(250,0,0,0.4)';
ctx.fill();
x += 2;
ctx.fillStyle = "rgba(34,45,23,0.4)";
ctx.fillRect(0, 0, can.width, can.height);
requestAnimationFrame(draw);
//ctx.clearRect(0,0,can.width,can.height);
}
draw();
<canvas id="canvas" style="background:rgba(34,45,23,0.4)"></canvas>
I think there is no object model behind the canvas, so you cannot access a "child object" like a "text object" and change it.
What you can do is that you draw the text again with a different color that overwrites the "pixels" of the canvas.
If you want to move the text, first you have to either clear the canvas or re-draw the text with a background/transparent color to get rid of the text in the previous position. Then you can draw the text in the new position.
I've never tried it but I think this would be the way to do it.
var canvas = document.getElementById("canvas"); //get the canvas dom object
var ctx = canvas.getContext("2d"); //get the context
var c = { //create an object to draw
x:0, //x value
y:0, //y value
r:5; //radius
}
var redraw = function(){ // this function redraws the c object every frame (FPS)
ctx.clearRect(0, 0, canvas.width, canvas.height); // clear the canvas
ctx.beginPath(); //start the path
ctx.arc(c.x, c.y, c.r, 0, Math.PI*2); //draw the circle
ctx.closePath(); //close the circle path
ctx.fill(); //fill the circle
requestAnimationFrame(redraw);//schedule this function to be run on the next frame
}
function move(){ // this function modifies the object
var decimal = Math.random() // this returns a float between 0.0 and 1.0
c.x = decimal * canvas.width; // mulitple the random decimal by the canvas width and height to get a random pixel in the canvas;
c.y = decimal * canvas.height;
}
redraw(); //start the animation
setInterval(move, 1000); // run the move function every second (1000 milliseconds)
Here is a fiddle for it.
http://jsfiddle.net/r4JPG/2/
If you want easing and translations, change the move method accordingly.
Hope it is allowed to advertise somebody's project.
Take a look at http://ocanvas.org/ you can get inspiration there.
It is object like canvas library. Allows you to handle events, make animations etc.
<html>
<head>
<title>Canvas Exam</title>
</head>
<body>
<canvas id="my_canvas" height="500" width="500" style="border:1px solid black">
</canvas>
<script>
var dom=document.getElementById("my_canvas");
var ctx=dom.getContext("2d");
var x1=setInterval(handler,1);
var x=50;
var y=50;
r=40;
function handler()
{
ctx.clearRect(0,0,500,500);
r1=(Math.PI/180)*0;
r2=(Math.PI/180)*360;
ctx.beginPath();
//x=x*Math.random();
x=x+2;
r=r+10*Math.random();
ctx.arc(x,y,r,r1,r2);
ctx.closePath();
ctx.fillStyle="blue";
ctx.fill();
ctx.stroke();
if(x>400)
{
x=50;
y=y+10;
}
r=40;
}
</script>
</body>
</html>

Categories

Resources