HTML Canvas: Rotate the Image 3D effect - html

How can i rotate the image (eg. to 45degrees) and squash the image. supposed i have a perfect square image. I can rotate it to any angle i want but i want to make the rotated square squashed, making the height 2/3 smaller than the width. the resulting image would be not a perfect rotated square but a squashed one.
do you know how can I achieve the effect?

Squishing a square is exceedingly easy, simply apply a scale:
ctx.scale(1, 2/3); // squish it to 2/3 vertical size
You'll have to translate it by the (opposite fraction * the height) / 2 to get it centered, though.
So to rotate and then squish a 200x200 square image you'd simply:
// rotation first
ctx.translate(100,100);
ctx.rotate(.3);
ctx.translate(-100,-100);
// than scale
ctx.translate(0,200 * (1/3) / 2) // move by half of the 1/3 space to center it
ctx.scale(1, 2/3); // squish it to 2/3 vertical size
ctx.drawImage(img, 0,0);
Example: http://jsfiddle.net/simonsarris/3Qr3S/

You can use 2D canvas to “fake” 3d by distorting width vs height
Do this by using context.drawImage and varying the width vs the height disproportionally
// draw image increasingly "squashed"
// to fake a 3d effect
ctx.drawImage(img,0,0,img.width,img.height,
left,
10,
(300-(right-left))/1,
300-(right-left)/1.5);
You can play with the distortion ratios to get different effects, but it’s all just “squishing”.
Here’s code and a Fiddle: http://jsfiddle.net/m1erickson/J2WfS/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px;}
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var left=1.0;
var right=300;
var sizing=.25;
var img=new Image();
img.onload=function(){
animate();
}
img.src="koolaidman.png";
function animate() {
// update scaling factors
left+=sizing;
right-=sizing;
if(left<0 || left>100){sizing = -sizing;}
console.log(left+"/"+right);
// clear and save the context
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
// draw image increasingly "squashed"
// to fake a 3d effect
ctx.drawImage(img,0,0,img.width,img.height,
left,
10,
(300-(right-left))/1,
300-(right-left)/1.5);
ctx.restore();
// request new frame
requestAnimFrame(function() {
animate();
});
}
animate();
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=235></canvas>
</body>
</html>

Related

HTML Canvas, How do you create a circle at the position of the mouse when clicked and then for the circle to increase in radius?

So, I have tried attempting this myself and have searched heavily online and I can't seem to solve this particular issue. I am attempting to make a very simple effect that looks like a very basic water ripple. I intend for the user to be able to click somewhere on the canvas, and for an empty circle (with a black stroke) to appear where the mouse has clicked (starting at a radius of zero), and continuously expand the radius as an animation.
I currently have this code:
<!DOCTYPE html>
<html>
<head>
<!-- Search Engine Optimisation (SEO) -->
<title> Ripple </title>
<meta description="Codelab assignment 3">
<meta keywords="Uni, assignment, ripple, interactive, discovery">
<!-- End of Metadata -->
<!-- Links -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<canvas id="myCanvas" width="1024" height="768" style="border: 1px solid"></canvas>
</body>
<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var radius = 0;
//Have a rectangle fill the canvas and add a hit region
//Call the ripple function from the rectangle function
//Track mouse position in rectangle
function ripple(e) {
// ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.beginPath();
ctx.arc(e.clientX,e.clientY,radius,0,2*Math.PI);
//ctx.closePath();
ctx.stokeStyle = "black";
ctx.stroke();
radius++;
requestAnimationFrame(ripple);
}
canvas.addEventListener('mousedown', ripple);
</script>
</html>
This is what it currently does:
Screenshot
I really appreciate any help!
You'd have to pass the mouse event when calling the ripple function through requestAnimationFrame.
also, you'll need to set the radius to 0 and clear running animation frame (if any) on mouse click
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var radius = 0;
var rAF;
function ripple(e) {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.beginPath();
ctx.arc(e.offsetX, e.offsetY, radius, 0, 2 * Math.PI);
ctx.stokeStyle = "black";
ctx.stroke();
radius++;
rAF = requestAnimationFrame(function() {
ripple(e);
});
}
canvas.addEventListener('mousedown', function(e) {
if (rAF) cancelAnimationFrame(rAF);
radius = 0;
ripple(e);
});
body{margin:10px 0 0 0;overflow:hidden}canvas{border:1px solid #ccc}
<canvas id="canvas" width="635" height="208"></canvas>
note: use e.offsetX and e.offsetY to get proper mouse coordinates relative to canvas.

is mouse in user drawn area on canvas

Basically, a user uploads a picture and then can paint on it, and save the result. Another user can then view the photo and if they click in the same area as painted, something happens.
So user 1 can make an area click-able for user 2 by drawing on the photo.
now the upload bit is fine, and painting with help from a tutorial and example I've got sussed out. But defining what area is click-able is a bit harder. For something like a rectangle its easy enough, I made an example.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var button = new Object();
button.x = 50;
button.y = 50;
button.width = 50;
button.height = 50;
button.rgb = "rgb(0, 0, 255)";
function drawbutton(buttonobject)
{
context.fillStyle = buttonobject.rgb;
context.fillRect (buttonobject.x, buttonobject.y, buttonobject.width, buttonobject.height);
context.strokeRect(buttonobject.x, buttonobject.y, buttonobject.width, buttonobject.height);
}
drawbutton(button);
function checkIfInsideButtonCoordinates(buttonObj, mouseX, mouseY)
{
if(((mouseX > buttonObj.x) && (mouseX < (buttonObj.x + buttonObj.width))) && ((mouseY > buttonObj.y) && (mouseY < (buttonObj.y + buttonObj.height))))
return true;
else
return false;
}
$("#myCanvas").click(function(eventObject) {
mouseX = eventObject.pageX - this.offsetLeft;
mouseY = eventObject.pageY - this.offsetTop;
if(checkIfInsideButtonCoordinates(button, mouseX, mouseY))
{
button.rgb = "rgb(0, 255, 0)";
drawbutton(button);
} else {
button.rgb = "rgb(255, 0, 0)";
drawbutton(button);
}
});
but when it comes to other shapes like circles, or just someone smothering the page, how would you go about detecting that ?
one thought I had was using the edited layer, making it hidden, and detecting a pixel color of say blue, from here but that limits the color use of the photo and im not entirely sure how to implement it. any other ideas ?
EDIT:
I figured out circles after some tinkering, using Pythagoras theorem to see if mouse coordinates are smaller than the radius, but this assumes circle center of 0,0, so then offset mouse by circles actual center. example
function checkIfInsideButtonCoordinates(buttonObj, mouseX, mouseY) {
actualX = mouseX - buttonObj.x
actualY = mouseY - buttonObj.y
mousesqX = actualX * actualX
mousesqY = actualY * actualY
sqR = buttonObj.r * buttonObj.r
sqC = mousesqX + mousesqY
if (sqC < sqR) return true;
else return false;
}
Here’s how to test whether user#2 is inside user#1’s paintings
Create a second canvas used to hit-test whether user#2 is inside of user#1’s paintings.
The hit-test canvas is the same size as the drawing canvas, but it only contains user#1’s paintings…not the image.
When user#1 is painting, also draw their paintings on the hit canvas.
When user#1 is done painting, save all their paintings from the hit canvas.
You have at least 2 ways to save user#1’s paintings from the hit canvas:
Serialize all the canvas commands needed to recreate the shapes/paths that user#1 paints.
Save the hit canvas as an image using canvas.toDataURL.
When user#2 clicks, check if the corresponding pixel on the hit canvas is filled or is transparent (alpha>0).
// getImageData for the hit-test canvas (this canvas just contains user#1's paintings)
imageDataData=hitCtx.getImageData(0,0,hit.width,hit.height).data;
// look at the pixel under user#2's mouse
// return true if that pixel is filled (not transparent)
function isHit(x,y){
var pixPos=(x+y*hitWidth)*4+3;
return( imageDataData[pixPos]>10)
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/etA5a/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:15px; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var hit=document.getElementById("hit");
var hitCtx=hit.getContext("2d");
var user2=document.getElementById("user2");
var ctx2=user2.getContext("2d");
var canvasOffset=$("#user2").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var imageDataData;
var hitWidth=hit.width;
var img=document.createElement("img");
img.onload=function(){
// left canvas: image+user#1 paintings
ctx.globalAlpha=.25;
ctx.drawImage(img,0,0);
ctx.globalAlpha=1.00;
scribble(ctx,"black");
// mid canvas: just user#1 paintings (used for hittests)
scribble(hitCtx,"black");
// right canvas: user#2
ctx2.drawImage(img,0,0);
imageDataData=hitCtx.getImageData(0,0,hit.width,hit.height).data;
}
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/colorhouse.png";
function scribble(context,color){
context.beginPath();
context.moveTo(70,2);
context.lineTo(139,41);
context.lineTo(70,41);
context.closePath();
context.rect(39,54,22,30);
context.arc(73,115,3,0,Math.PI*2,false);
context.fillStyle=color;
context.fill();
}
function handleMouseMove(e){
var mouseX=parseInt(e.clientX-offsetX);
var mouseY=parseInt(e.clientY-offsetY);
// If user#2 has a hit on user#1's painting, mid-canvas turns red
var color="black";
if(isHit(mouseX,mouseY)){ color="red"; }
scribble(hitCtx,color);
}
function isHit(x,y){
var pixPos=(x+y*hitWidth)*4+3;
return( imageDataData[pixPos]>10)
}
$("#user2").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Left: original image with user#1 painting</p>
<p>Mid: user#1 painting only (used for hit-testing)</p>
<p>Right: user#2 (move mouse over hit areas)</p>
<canvas id="canvas" width=140 height=140></canvas>
<canvas id="hit" width=140 height=140></canvas>
<canvas id="user2" width=140 height=140></canvas><br>
</body>
</html>

Draw a trapezoid in canvas

Could somebody advice how to transform image on canvas from rectangle to trapeze?
For example I have a image-rectangle 100x200 and canvas 300x300.
Then I want to transform my image and put corners in the following points:
100,0; 200,0;
0,300; 300,300
And transformation should re-size image to fit new figure.
I get it, you want to do a y-rotation (like the star wars scrolling intro).
Not possible with the current canvas 2d context transform matrix
The 2d transformation matrix looks like this with the last values fixed at 0,0,1:
M11, M21, dx
M12, M22, dy
0, 0, 1
You would need a y-rotation matrix that looks like this:
cosA, 0, sinA
0, 1, 0
-sinA, 0, cosA
But you can't set -sinA, 0, cosA
[Previous answer]
Here's how you change an rectangle-containing-image to a trapezoid-containing-image
You have to draw each leg of the trapeze individually. But you can draw 3 of the sides and then use closePath() to automatically draw the 4th side.
This code animates between the rectangle and the trapezoid and scales the clipped image. This code assumes you want the image presented in a way that keeps the scaling image as large as possible.
Here's code and a Fiddle: http://jsfiddle.net/m1erickson/7T2YQ/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px;}
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.lineWidth=5;
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var left=1.0;
var right=300;
var sizing=.25;
var img=new Image();
img.onload=function(){
animate();
}
img.src="http://dl.dropbox.com/u/139992952/stackoverflow/KoolAidMan.png";
function animate() {
// update scaling factors
left+=sizing;
right-=sizing;
if(left<0 || left>100){sizing = -sizing;}
console.log(left+"/"+right);
// clear and save the context
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
// draw the clipping trapezoid
defineTrapezoid(left,right);
ctx.clip();
// draw trapezoid border
defineTrapezoid(left,right);
ctx.stroke();
// draw image clipped in trapeze
var imgX=left/2;
var imgY=left;
var w=300-left;
ctx.drawImage(img,0,0,img.width,img.height,imgX,imgY,w,w);
ctx.restore();
// request new frame
requestAnimFrame(function() {
animate();
});
}
animate();
function defineTrapezoid(left,right){
ctx.beginPath();
ctx.moveTo(left,0);
ctx.lineTo(right,0);
ctx.lineTo(300,300);
ctx.lineTo(0,300);
ctx.closePath();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Canvas: Click event on line

Please take a look at this little example. The clickhandler only works if you click in the middle of the line. It seems that the method isPointInPath does not consider the width of the line. Is there a way to solve this problem?
Yes, you are correct.
The new isPointInPath() works only on the centerline of a "fat" line--not the full width of the line.
It's more user friendly on closed shapes that are more than 1 pixel wide ;)
A Workaround for your exact question: Instead of drawing a fat line, draw a 20px wide rectangle.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/QyWDY/
This code uses basic trigonometry to create a rectangle around a line. In the mousedown event handler, it redraws the rectangle transparently and then tests isPointInPath().
If you need to test a poly-line, you can use these same principles to make rectangle-lines for each segment of your poly-line.
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// get canvas's relative position
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
// line specifications
var x1=50;
var y1=50;
var x2=300;
var y2=100;
// draw the lineRectangle
var lineRect=defineLineAsRect(x1,y1,x2,y2,20);
drawLineAsRect(lineRect,"black");
// overlay the line (just as visual proof)
drawLine(x1,y1,x2,y2,3,"red");
function drawLine(x1,y1,x2,y2,lineWidth,color){
ctx.fillStyle=color;
ctx.strokeStyle=color;
ctx.lineWidth=lineWidth;
ctx.save();
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
ctx.restore();
}
function drawLineAsRect(lineAsRect,color){
var r=lineAsRect;
ctx.save();
ctx.beginPath();
ctx.translate(r.translateX,r.translateY);
ctx.rotate(r.rotation);
ctx.rect(r.rectX,r.rectY,r.rectWidth,r.rectHeight);
ctx.translate(-r.translateX,-r.translateY);
ctx.rotate(-r.rotation);
ctx.fillStyle=color;
ctx.strokeStyle=color;
ctx.fill();
ctx.stroke();
ctx.restore();
}
function defineLineAsRect(x1,y1,x2,y2,lineWidth){
var dx=x2-x1; // deltaX used in length and angle calculations
var dy=y2-y1; // deltaY used in length and angle calculations
var lineLength= Math.sqrt(dx*dx+dy*dy);
var lineRadianAngle=Math.atan2(dy,dx);
return({
translateX:x1,
translateY:y1,
rotation:lineRadianAngle,
rectX:0,
rectY:-lineWidth/2,
rectWidth:lineLength,
rectHeight:lineWidth
});
}
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// draw our lineRect
drawLineAsRect(lineRect,"transparent");
// test if hit in the lineRect
if(ctx.isPointInPath(mouseX,mouseY)){
alert('Yes');
}
}
canvas.addEventListener("mousedown", handleMouseDown, false);
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=310 height=115></canvas>
</body>
</html>

How do I clear text from the <canvas> element?

I have put text on an image in a <canvas> tag (the text was taken from an input box).
Now if I put a new text on the <canvas>, it is imposed on the previous text. How do I clear the existing text on the canvas before putting in the new text?
I have tried resetting the canvas by assigning canvas.width but the text stays on. Any help people?
If you know you're going to be adding and removing text a lot, it might make sense to keep track of the old text. Then you could just use this:
context.fillStyle = '#ffffff'; // or whatever color the background is.
context.fillText(oldText, xCoordinate, yCoordinate);
context.fillStyle = '#000000'; // or whatever color the text should be.
context.fillText(newText, xCoordinate, yCoordinate);
This way you don't have to redraw the whole canvas every time.
You use context.clearRect(), but first you have to figure out the rectangle to clear. This is based off a number of factors, such as the size of the text and the textAlign property of the canvas context when the text was originally drawn. The code below would be for the draw method of a object that draws text into a canvas context, as such it has properties for x, y, text size, horizontal alignment etc. Note that we always store the last piece of text drawn so we can clear an appropriately sized rectangle when the value is next changed.
this.draw = function() {
var metrics = this.ctx.measureText(this.lastValue),
rect = {
x: 0,
y: this.y - this.textSize / 2,
width: metrics.width,
height: this.textSize,
};
switch(this.hAlign) {
case 'center':
rect.x = this.x - metrics.width / 2;
break;
case 'left':
rect.x = this.x;
break;
case 'right':
rect.x = this.x - metrics.width;
break;
}
this.ctx.clearRect(rect.x, rect.y, rect.width, rect.height);
this.ctx.font = this.weight + ' ' + this.textSize + ' ' + this.font;
this.ctx.textAlign = this.hAlign;
this.ctx.fillText(this.value, this.x, this.y);
this.lastValue = this.value;
}
You need to use clearRect(x, y, w, h); More details at MDC
If you can't clear other drawings in the same area of the text, another solution is to have two canvas, one over the other:
<div style="position: relative;">
<canvas id="static" width="1350" height="540" style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
<canvas id="dynamic" width="1350" height="540" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
</div>
Then you can use the first for static drawings that don't need to be removed, and the other one with dynamic drawings. In your case you can put the text in the dynamic canvas and remove it with clearRect before drawing again.
context.clearRect(0, 0, canvas.width, canvas.height);
I'm not sure about how to clear the text off the image before you put the next piece of text.
If the background of the canvas is constant; and your only changing the text you could layer two canvas elements. The background, and a transparent top layer for text that can be removed and a new one inserted when you want to update the text.
not sure if it would work, but you could try redrawing the text in the background color
Here is the best approach and it worked for me. Clear function is just to clear the recaptcha. So just call this function when you refresh.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='main.css'>
<script src='main.js'></script>
</head>
<body>
<h4>Canvas</h4><canvas width="200" height="100" id="cnv1"></canvas><br/>
<button id="clear_cnv">Clear</button> - <button id="setnr_cnv">Set Nr</button>
<script type="text/javascript">
// <![CDATA[
// function to clear the canvas ( https://coursesweb.net/ )
// cnv = the object with the canvas element
function clearCanvas(cnv) {
var ctx = cnv.getContext('2d'); // gets reference to canvas context
ctx.beginPath(); // clear existing drawing paths
ctx.save(); // store the current transformation matrix
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, cnv.width, cnv.height);
ctx.restore(); // restore the transform
}
// sets and adds a random number in canvas
// cnv = the object with the canvas element
function addNrCnv(cnv) {
// gets a random number between 1 and 100
var nr = Math.floor(Math.random() * 100 + 1);
var ctx = cnv.getContext('2d'); // gets reference to canvas context
// create text with the number in canvas (sets text color, font type and size)
ctx.fillStyle = '#00f';
ctx.font = 'italic 38px sans-serif';
ctx.fillText(nr, 80, 64);
}
// get a reference to the <canvas> tag
var cnv1 = document.getElementById('cnv1');
// register onclick event for #clear_cnv button to call the clearCanvas()
document.getElementById('clear_cnv').onclick = function() { clearCanvas(cnv1); }
// register onclick event for #setnr_cnv button to call the addNrCnv()
document.getElementById('setnr_cnv').onclick = function() { addNrCnv(cnv1); }
// ]]>
</script>
</body>
</html>