image resize and then rotate in canvas - javascript - javascript

I am using an image with size 1024 x 768 and I have a canvas size 300 x 300 so I want to resize my image first to 300 x 300 and then rotate it within the canvas proportionally.
I am using following code but it is resizing the image but rotating some elements outside the canvas. So if you click right then you dont see anything and then hit right again then you will the image with down rotated.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var degrees=0;
var image=document.createElement("img");
image.onload=function(){
ctx.drawImage(image,0,0,300,300);
}
image.src="http://media1.santabanta.com/full1/Outdoors/Landscapes/landscapes-275a.jpg";
image.width = 300;
image.height = 300;
$("#clockwise").click(function(){
degrees+=90
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(300,300);
ctx.rotate(degrees*Math.PI/180);
ctx.drawImage(image,0,0,300,300);
ctx.restore();
});
Please check my code in JSFiddle as well
http://jsfiddle.net/6ZsCz/914/

Try this variation.
Translate to the center of the canvas.
DrawImage with an [x,y] offset of image.width/2 & image.height/2. This offset is required because translate effectively makes the canvas centerpoint[150,150] to be the new canvas origin[0,0]. You need the negative offset to pull the drawing leftward and upward to compensate for the new origin.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var degrees=0;
var image=document.createElement("img");
image.onload=function(){
ctx.drawImage(image,0,0,300,300);
}
image.src="http://media1.santabanta.com/full1/Outdoors/Landscapes/landscapes-275a.jpg";
$("#clockwise").click(function(){
degrees+=90
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(150,150);
ctx.rotate(degrees*Math.PI/180);
ctx.drawImage(image,0,0,image.width,image.height,-150,-150,300,300);
ctx.restore();
});
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="canvas" width=300 height=300></canvas><br>
<button id="clockwise">Rotate right</button>

Related

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>

Canvas Element - Rotation

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

Canvas DrawImage() poor quality [duplicate]

This question already has answers here:
Html5 canvas drawImage: how to apply antialiasing
(6 answers)
Closed 8 years ago.
I have a problem with Html5 canvas
i draw an image but its quality becomes very poor
after i draw it with canvas it becomes this
my code is here
<script type="text/javascript">
$canvasWidth = $('#canvas').width;
$canvasHeight = $('#canvas').height;
var alpha = 0.0;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function draw(){
var delta = 0.05;
ctx.clearRect(0,0,$canvasWidth, $canvasHeight);
ctx.globalAlpha = alpha;
var logo= new Image();
WandioLight.onload = function(){
ctx.drawImage(logo, 0, 0, 250, 167);
};
logo.src = "logo.png";
alpha += delta;
if(alpha > 1.0){
return false;
}
setTimeout(draw, 50);
}
You can incrementally scale your image down for better results.
Since your final size is 1/4 the original size, you could:
scale the 1000x669 image in half to 500x334 onto a temp canvas
scale the 500x335 canvas in half to 250x167 onto the main canvas
Here's example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var img=new Image();
img.onload=start;
img.src="https://ictcluster.ge/wp-content/uploads/2018/09/wandio-logo-1-1024x724.png";
function start(){
// scale the 1000x669 image in half to 500x334 onto a temp canvas
var c1=scaleIt(img,0.50);
// scale the 500x335 canvas in half to 250x167 onto the main canvas
canvas.width=c1.width/2;
canvas.height=c1.height/2;
ctx.drawImage(c1,0,0,250,167);
}
function scaleIt(source,scaleFactor){
var c=document.createElement('canvas');
var ctx=c.getContext('2d');
var w=source.width*scaleFactor;
var h=source.height*scaleFactor;
c.width=w;
c.height=h;
ctx.drawImage(source,0,0,w,h);
return(c);
}
body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

faster method of copying image data

i have the following script
// copy image data to secondary canvas
var pixelData = contextSource.getImageData(x - (lineWidth/2), y - (lineWidth/2), lineWidth, lineWidth);
var tmpCanvas = document.createElement('canvas');
tmpCanvas.width = tmpCanvas.height = lineWidth;
var tmpContext = tmpCanvas.getContext('2d');
tmpContext.putImageData(pixelData, 0, 0);
contextDest.save();
contextDest.arc(x, y, (lineWidth/2), 0, 2*Math.PI);
contextDest.clip();
contextDest.drawImage(tmpCanvas, x - (lineWidth/2), y - (lineWidth/2));
contextDest.restore();
the script is sampling image data from canvas source when mouse is moving over the source, then copy it to destination. the script is working good, but a bit slow. here is the result when i move the mouse pointer a bit faster.
is there any faster method than mine? please help
#Banana has a good point.
Instead of drawing just the mouse positions, try connecting the positions into a single continuous line..
If you want the rounded effect in your illustration, you can set:
context.lineCap='round';
context.lineJoin='round';
As to masking faster...
A much faster way of masking your image is to:
draw your single line on the second canvas.
Use compositing to make all new draws be visible only where existing pixels are opaque. This compositing is 'source-in' and is set using: context.globalCompositeOperation='source-in'
Draw your image onto the second canvas. The image will show only where the line was.
Using compositing is much faster because compositing is hardware accelerated and is optimized by the browser.
That compositing code might look like this:
function draw(){
// clear the second canvas
ctx1.clearRect(0,0,cw,ch);
// draw your continuous line
ctx1.beginPath();
ctx1.moveTo(points[0].x,points[0].y);
for(var i=1;i<points.length;i++){
p=points[i];
ctx1.lineTo(p.x,p.y);
}
ctx1.stroke();
// set compositing so new draws only appear in
// existing opaque pixels
ctx1.globalCompositeOperation='source-in';
// draw the image
// the image will only be visible in the exising line
ctx1.drawImage(img,0,0);
// be tidy! return compositing to its default mode
ctx1.globalCompositeOperation='source-over';
}
Here's an example and Demo:
var canvas1=document.getElementById("canvas1");
var ctx1=canvas1.getContext("2d");
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
var isDown=false;
var startX;
var startY;
var points=[];
var cw,ch;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/tempHouse%201.jpg";
function start(){
cw=canvas.width=canvas1.width=img.width;
ch=canvas.height=canvas1.height=img.height;
ctx1.lineCap = "round";
ctx1.lineJoin = "round";
ctx1.lineWidth=20;
ctx.drawImage(img,0,0);
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}
function draw(){
// clear the second canvas
ctx1.clearRect(0,0,cw,ch);
// draw your continuous line
ctx1.beginPath();
ctx1.moveTo(points[0].x,points[0].y);
for(var i=1;i<points.length;i++){
p=points[i];
ctx1.lineTo(p.x,p.y);
}
ctx1.stroke();
// set compositing so new draws only appear in
// existing opaque pixels
ctx1.globalCompositeOperation='source-in';
// draw the image
// the image will only be visible in the exising line
ctx1.drawImage(img,0,0);
// be tidy! return compositing to its default mode
ctx1.globalCompositeOperation='source-over';
}
function handleMouseDown(e){
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
points.length=0;
points.push({x:mouseX,y:mouseY});
isDown=true;
}
function handleMouseUp(e){
e.preventDefault();
e.stopPropagation();
isDown=false;
draw();
}
function handleMouseOut(e){
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
points.push({x:mouseX,y:mouseY});
isDown=false;
draw();
}
function handleMouseMove(e){
if(!isDown){return;}
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
points.push({x:mouseX,y:mouseY});
draw();
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="canvas" width=300 height=300></canvas><br>
<canvas id="canvas1" width=300 height=300></canvas>

rotating 2 images on canvas

I have to draw 3 images on the canvas and need to rotate 2 of the images.
The images are like
1. circular with a vertical straight line
2. just an horizontal line
3. Big circular image
I need to rotate the 1st 2 images in the center of the canvas.
var canvas = document.getElementById('NewImage');
var context = canvas.getContext('2d');
context.canvas.width = window.innerWidth;
context.canvas.height = window.innerHeight*0.7;
var imageObj = new Image();
var imageObj2 = new Image();
var imageObj3 = new Image();
imageObj.onload = function() {
context.save();
context.translate(imageObj.width/2,imageObj.height/2);
context.rotate(-10*Math.PI/180);
//context.translate(-imageObj.width/2,-imageObj.height/2);
context.drawImage(imageObj,-(imageObj.width/2),-(imageObj.height/2),context.canvas.width,context.canvas.height*0.85);
context.restore();
context.save();
context.globalCompositeOperation="source-over";
context.translate(imageObj2.width/2,imageObj2.height/2);
context.rotate(-10*Math.PI/180);
context.translate(-imageObj2.width/2,-imageObj2.height/2);
context.drawImage(imageObj2, x, y,context.canvas.width,6);
context.restore();
//context.rotate(10*Math.PI/180);
context.drawImage(imageObj3, 0, 0,context.canvas.width,context.canvas.height*0.9);
};
imageObj.src = 'canvas/inner_circle_blackline_vertical.png';
imageObj2.src = 'canvas/horizontal.png';
imageObj3.src = 'canvas/outer_circle.png';
When i try to rotate, the images are not rotating in center. when 1st 2 images rotates it has to look like "X" symbol.
How will i rotate in center of the canvas.
Thanks:)
As designed, your imageObj2 and imageObj3 will never load.
Here is a generic image loader that will load all your images and store them in an array called imgs[].
When all your images have fully loaded, the render() function will be called. That’s where you start drawing.
// This is an image loader
// When render() is called, all your images are fully loaded
var imgURLs = [
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png"];
var imgs=[];
var imgCount=0;
pre_load();
function pre_load(){
for(var i=0;i<imgURLs.length;i++){
var img=new Image();
imgs.push(img);
img.onload=function(){
if(++imgCount>=imgs.length){
// images are now fully loaded
render();
}
}
img.src=imgURLs[i];
}
}
In render(), you just draw your images.
Since the same action (rotating an image) is done repeatedly, you can create a helper function to do the rotated drawing. Here the helper function is drawImageAtAngle.
// draw the rotated lines on the canvas
function render(){
var x=canvas.width/2;
var y=canvas.height/2;
drawImageAtAngle(imgs[0],x,y,-45);
drawImageAtAngle(imgs[2],x,y,45);
drawImageAtAngle(imgs[1],x,y,0);
}
Here the helper function that rotates a supplied image to a supplied angle:
function drawImageAtAngle(image,X,Y,degrees){
var radians=degrees*Math.PI/180;
var halfWidth=image.width/2;
var halfHeight=image.height/2;
ctx.beginPath();
ctx.save();
ctx.translate(X,Y);
ctx.rotate(radians);
ctx.drawImage(image,-halfWidth,-halfHeight);
ctx.restore();
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/ZShWW/
<!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:10px;}
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// This is an image loader
// When render() is called, all your images are fully loaded
var imgURLs = [
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png"];
var imgs=[];
var imgCount=0;
pre_load();
function pre_load(){
for(var i=0;i<imgURLs.length;i++){
var img=new Image();
imgs.push(img);
img.onload=function(){
if(++imgCount>=imgs.length){
// images are now fully loaded
render();
}
}
img.src=imgURLs[i];
}
}
// draw the rotated lines on the canvas
function render(){
var x=canvas.width/2;
var y=canvas.height/2;
drawImageAtAngle(imgs[0],x,y,-45);
drawImageAtAngle(imgs[2],x,y,45);
drawImageAtAngle(imgs[1],x,y,0);
}
function drawImageAtAngle(image,X,Y,degrees){
var radians=degrees*Math.PI/180;
var halfWidth=image.width/2;
var halfHeight=image.height/2;
ctx.beginPath();
ctx.save();
ctx.translate(X,Y);
ctx.rotate(radians);
ctx.drawImage(image,-halfWidth,-halfHeight);
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<p>This is the line image</p>
<img src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png">
<p>The line image rotated at center of canvas</p>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
To find the center of the canvas you have to use the dimensions of the canvas. In your code you are using the dimensions of the image. That is, this line:
context.translate(imageObj.width/2,imageObj.height/2);
should probably be:
context.translate(canvas.width/2,canvas.height/2);
That moves you to the center of the canvas. The rotation then occurs around that center. You are then drawing the image centered on the origin. That part looks correct.
You will then reverse the rotation and then the translation.

Categories

Resources