drawImage and resize to Canvas - javascript

I have an image which is 1836 x 3264 I want to drawImage() to canvas and resize to 739 x 1162.
After reading the documentation I thought this could be accomplished with the following:
ctx.drawImage(image, 0, 0, 739, 1162);
I have also tried:
ctx.drawImage(image, 0, 0, 1836, 3264, 0, 0, 739, 1162);
Both show only a small part of the full image instead of shrinking it down.
How do I pass through the values to resize from 1836 x 3264 -> 739 x 1162 ?

What you have looks correct, so you might double-check for a typo somewhere.
[additional thought: Is your image really 1836x3264 and not 3264x1836.]
Here is working code and a Fiddle: http://jsfiddle.net/m1erickson/MLGr4/
<!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");
img=new Image();
img.onload=function(){
canvas.width=400;
canvas.height=300;
ctx.drawImage(img,0,0,img.width,img.height,0,0,400,300);
}
img.src="http://www.onestopwebmasters.com/wp-content/uploads/2011/06/eitai-bridge.jpg";
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=100 height=100></canvas>
</body>
</html>

Related

Using destination-over to save background and actual sketch

I've read this and a few other questions, and it is clear I need to use destination-over to save the background and the sketch by display the new image over the old one.
I'm using Sketch.JS with my code as such:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
$('#myCanvas').sketch({
defaultColor: "red"
});
$('#download').click(function() {
ctx.globalCompositeOperation = "destination-over";
img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = 'http://lorempixel.com/400/200/';
ctx.drawImage(img, 0, 0);
$('#url').text(c.toDataURL('/image/png'));
window.open(c.toDataURL('/image/png'));
});
#myCanvas {
background: url(http://lorempixel.com/400/200/);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/intridea/sketch.js/gh-pages/lib/sketch.js"></script>
<canvas id="myCanvas"></canvas>
<input type='button' id='download' value='download'>
<span id='url'></span>
Fiddle
But that doesn't help. Clicking 'download' still only produces the sketch. Now, it seems I don't understand how I need to use destination-over properly. W3Schools doesn't seem to help.
Could anyone point me in the right direction please?
Assume you have a SketchJS canvas on top of an image containing a background:
#wrapper{positon:relative;}
#bk,#myCanvas{position:absolute;}
<div id='wrapper'>
<img crossOrigin='anonymous' id=bk src='yourImage.png'>
<canvas id="myCanvas" width=500 height=300></canvas>
</div>
Then when you want to combine the Sketch with the background and save it as an image you can use destination-over compositing to draw the background "under" the existing Sketch.
ctx.globalCompositeOperation='destination-over';
ctx.drawImage(bk, 0, 0);
Here's example code:
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://rawgit.com/intridea/sketch.js/gh-pages/lib/sketch.js"></script>
<style>
body{ background-color: ivory; }
#wrapper{positon:relative;}
#bk,#myCanvas{position:absolute;}
</style>
<script>
$(function(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
$('#myCanvas').sketch({ defaultColor: "red" });
$('#download').click(function() {
var img=document.getElementById('bk');
ctx.globalCompositeOperation='destination-over';
ctx.drawImage(bk, 0, 0);
ctx.globalCompositeOperation='source-over';
var html="<p>Right-click on image below and Save-Picture-As</p>";
html+="<img src='"+c.toDataURL()+"' alt='from canvas'/>";
var tab=window.open();
tab.document.write(html);
});
}); // end $(function(){});
</script>
</head>
<body>
<h4>Drag to sketch on the map.</h4>
<button id=download>Download</button>
<div id='wrapper'>
<img crossOrigin='anonymous' id=bk src='https://dl.dropboxusercontent.com/u/139992952/multple/googlemap1.png'>
<canvas id="myCanvas" width=459 height=459></canvas>
</div>
</body>
</html>

Zoom and pan HTML5 canvas - library

I'm trying to implement zooming and panning a canvas which contains a picture.
I found this example http://phrogz.net/tmp/canvas_zoom_to_cursor.html, but the transformations are applied on the picture withing the canvas, not on the canvas itself.
I don't understand the code completely, so I didn't manage to customize it for my needs.
Can someone help me with that?
Or, if you could recommend me some good library suitable for my needs, that would be great.
Thanks.
Check out the transformation methods available on the context object.
Context.scale will allow you to scale your content.
Context.translate will allow you to offset the drawing of your content to create your panning effect.
If you want 2 overlaying canvases to maintain their aspect ratio then you would scale & translate both canvases by the same amount.
Here's example code and a Demo: http://jsfiddle.net/m1erickson/H6UMN/
<!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; }
#wrapper{position:relative;}
canvas{position:absolute; border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvas1=document.getElementById("canvas1");
var ctx1=canvas1.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 cw=canvas.width;
var ch=canvas.height;
var scaleFactor=1.00;
var panX=0;
var panY=0;
var circleX=150;
var circleY=150;
var radius=15;
drawTranslated();
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#scaledown").click(function(){ scaleFactor/=1.1; drawTranslated(); });
$("#scaleup").click(function(){ scaleFactor*=1.1; drawTranslated(); });
$("#panleft").click(function(){ panX-=10; drawTranslated(); });
$("#panright").click(function(){ panX+=10; drawTranslated(); });
function drawTranslated(){
ctx.clearRect(0,0,cw,ch);
ctx.save();
ctx.translate(panX,panY);
ctx.scale(scaleFactor,scaleFactor);
ctx.beginPath();
ctx.rect(circleX-radius,circleY-radius,radius*2,radius*2);
ctx.closePath();
ctx.fillStyle="blue";
ctx.fill();
ctx.restore();
ctx1.clearRect(0,0,cw,ch);
ctx1.save();
ctx1.translate(panX,panY);
ctx1.scale(scaleFactor,scaleFactor);
ctx1.beginPath();
ctx1.arc(circleX,circleY,radius,0,Math.PI*2);
ctx1.closePath();
ctx1.fillStyle="red";
ctx1.fill();
ctx1.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<button id=scaledown>Scale Down</button>
<button id=scaleup>Scale Up</button>
<button id=panleft>Pan Left</button>
<button id=panright>Pan Right</button><br>
<div id=wrapper>
<canvas id="canvas" width=350 height=300></canvas>
<canvas id="canvas1" width=350 height=300></canvas>
</div>
</body>
</html>

Smooth Zooming in Canvas via button instead of mousewheel

I am trying to implement something like a smooth zoom in a Canvas application.
I am already able to zoom to a predefined zoom level using this:
$("#zoomToView").click(function () {
paper.view.zoom=5.0;
});
Most of the examples for smooth zomming pertain to mouse-wheel implementations but I would like to use a button instead that zooms to a pre-defined level and back.
I have the impression that the implementantion has something to do with a FOR loop and some kind of adaptive delay that gets bigger as the loop count increases.
Any ideas?
I am using Paper.js as my canvas library but that should not be a factor in finding a solution.
Here's an example using native canvas, but you can substitute paper.js if desired.
The concept is to continuously run an animation loop that only resizes the image if your button is down.
http://jsfiddle.net/SW5jL/3/
Example code:
<!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");
var cw=canvas.width;
var ch=canvas.height;
var iw,ih;
var img=new Image();
img.onload=start;
img.src="https://www.w3schools.com/css/img_fjords.jpg";
function start(){
iw=img.width;
ih=img.height;
$("#test").mousedown(function(){ doAnimation=true; });
$("#test").mouseup(function(){ doAnimation=false; });
$("#test").mouseout(function(){ doAnimation=false; });
requestAnimationFrame(animate);
ctx.drawImage(img,cw/2-iw/2,ch/2-ih/2);
}
var scale=1.00;
scaleDirection=0.01;
var minScale=0.50;
var maxScale=1.50;
var doAnimation=false;
function animate(){
requestAnimationFrame(animate);
if(doAnimation){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(img,
0,0,iw,ih,
(cw-iw*scale)/2,(ch-ih*scale)/2,iw*scale,ih*scale
);
scale+=scaleDirection;
if(scale<minScale || scale>maxScale){
scaleDirection*=-1;
scale+=scaleDirection;
}
}
}
}); // end $(function(){});
</script>
</head>
<body>
<button id="test">Animate</button><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

canvas arc y-axis overflow

I am trying to draw an arc within a canvas and i want to make that arc to fill the canvas.
i tried to make the arc half canvas's size and i works perfectly but when i increase the radius to be same width as the canvas i find an error...as for arc width its good but for the height it increases alot, disappears and i feel like radius is doubling the y-axis.
and when i check it in jsFiddle it works perfectly...maybe i have to do with some css or something?
var canvas = document.getElementById("canvas2");
var context = canvas.getContext("2d");
var counterClockwise = false;
var x = canvas.width /2;
var y = canvas.height /2;
context.beginPath();
context.arc(x, y, x-9, 0, 2*Math.PI);
context.stroke();
and this the html body:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/font-awesome.css" />
</head>
<body>
<canvas id="canvas2" style="width:207px;height:207px"></canvas>
</body>
</html>
Set the width and height on the canvas element itself, not in CSS:
canvas.width=207;
canvas.height=207;
Setting width and height in css will distort your drawings (as you've discovered).
Also, when you draw an arc which you intend to be a circle, be sure to call context.closePath();
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/adGfS/
<!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("canvas2");
var context = canvas.getContext("2d");
canvas.width=207;
canvas.height=207;
var x = canvas2.width /2;
var y = canvas2.height /2;
context.beginPath();
context.arc(x, y, x-9, 0, 2*Math.PI);
context.closePath();
context.stroke();
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas2"></canvas>
</body>
</html>

Display whole image in circulr shape using Javascript or HTML5

How can I display whole image in circulr shape using Javascript or HTML5. I tried the code below but with this code only part of the image will be converted into circular shape. How can I make the whole display in circular shape?
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#myCanvas {
border: 1px solid #9C9898;
}
</style>
<script type="text/javascript" >
</script>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<div id="myCanvas"></div>
<script>
var ctx = document.getElementById('myCanvas').getContext("2d");
ctx.arc(100,100, 50, 0, Math.PI*2,true); // you can use any shape
ctx.clip();
var img = new Image();
img.addEventListener('load', function(e) {
ctx.drawImage(this, 0, 0, 200, 300);
}, true);
img.src="images/hospital_review_profile_placeholder.png";
</script>
</body>
</html>
Instead of using ctx.clip(), you would resize and reposition your image to fit in your circle.
Here is code that will resize your image to its largest size that will fit in the circle.
Then the code positions the resized image properly in the circle.
Here is a Fiddle --- http://jsfiddle.net/m1erickson/s6MzZ/
<!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");
var radius=50; // circle radius
var fullWidth=200; // actual width of image in pixels
var fullHeight=300; // actual height of image in pixels
var centerX=100; // center X coordinate of the circle
var centerY=100; // center Y coordinate of the Circle
// the image must be resized to fit into the circle
// Call CalcResizedImageDimensions() to get the resized width/height
var size=CalcResizedImageDimensions(radius,fullWidth,fullHeight);
var rectX=centerX-size.width/2; // the X coordinate of the resized rectangle
var rectY=centerY-size.height/2 // the Y coordinate of the resized rectangle
ctx.beginPath();
ctx.arc(centerX,centerY,radius,0,Math.PI*2,true);
// I illustrate with just a rectangle
// you would drawImage() instead
ctx.rect(rectX,rectY,size.width,size.height);
ctx.stroke();
function CalcResizedImageDimensions(r,w,h){
var d=2*r;
var newH=(d*h)/Math.sqrt(w*w+h*h);
var newW=w/h*newH;
return({width:newW,height:newH});
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=200 height=200></canvas>
</body>
</html>

Categories

Resources