I am trying to resize the original photo(corgi.png) to 100 x 100. I am able to to show the original photo by using this code: context.drawImage(image, 0, 0); but the resized photo (100x100) is not showing. What am I doing wr0ng?
let canvas = document.getElementById("demoCanvas");
let context = canvas.getContext("2d");
let image = new Image();
image.src = "corgi.png";
image.onload = () => {
context.drawImage(image, 0, 0);
let smallImageData = new ImageData(100,100);
context.putImageData(smallImageData, 500, 0);
};
I don't understand why you are using drawImage and putImageData both here.
The syntax for drawImage is enough to get the required result:
drawImage(image, dx, dy, dWidth, dHeight)
Using this, your code would look like:
let image = new Image();
image.src = "corgi.png";
image.onload = () => {
context.drawImage(image, 500, 0, 100, 100);
};
Note: Make sure your canvas width is greater than dx + dWidth, i.e. 500 + 100 = 600. Otherwise your image will not be visible.
let canvas = document.getElementById("demoCanvas");
canvas.width = 1000; // >=600
Related
I have the following html file which draws an image on the canvas.
<canvas id="canvas"width="800"height="800"></canvas>
<script>
var canvas = document.getElementById('canvas')
let ctx = canvas.getContext('2d')
let img = new Image()
img.src = 'https://clipartspub.com/images/circle-clipart-blue-1.jpg'
img.onload = function(){
ctx.drawImage(img,300,300,300,300)
}
</script>
It works fine, however I would like to instead draw a cropped version of this image, for example, the bottom right quarter of the image. Is this possible?
You have to use the below implementation of drawImage to achieve that
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
Check the docs here
var canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let img = new Image();
img.src = "https://clipartspub.com/images/circle-clipart-blue-1.jpg";
img.onload = function () {
const width = img.width;
const height = img.height;
ctx.drawImage(
img, // Source image
width / 2, // Start at this x of image
height / 2, // Start at this y of image
width / 2, // Till this width of image
height / 2, // Till this height of image
0, // Start at this x of canvas
0, // Start at this y of image
300, // Till this width of canvas
300 // // Till this height of canvas
);
};
<canvas id="canvas"width="800"height="800"></canvas>
You can also use canvas.width and canvas.height in the canvas values used above for a better scaled result.
I got an image, it could be of every size but I need to take the center area of 86x86. Also I've to do that in javascript when a new image is loaded, replacing the old one.
At the end of the code I need to have my 's src updated with the new image.
function loadedImage(elem,gCount){
var crop = { //just messing with numbers
top : 10,
left : 10,
right : 20,
bottom : 20,
};
var file = elem.files[0]; //I take the loaded image
var img = document.getElementsByName('imag')[gCount]; //I take the interessed <img>
var canvas = document.createElement("canvas"); //create canvas
canvas.width = crop.right - crop.left; //set dimensions
canvas.height = crop.bottom - crop.top;
var ctx = canvas.getContext("2d"); // so we can draw
var image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.width = img.width;
image.height = img.height;
image.src = window.URL.createObjectURL(file);
ctx.drawImage(image, -crop.left, -crop.top);
image.src = canvas.toDataURL("image/png");
img.src = image.src;
}
No image is shown
Use a load event listener to wait for your image to load. Once it's ready, you can then start drawing.
To draw the center part of your image, the source x-coordinate should be half the width of your image, minus half the width of the crop. (The source y-coordinate can be calculated in a similar way.)
var input = document.getElementsByName('input')[0];
input.addEventListener('change', function (e) {
var file = e.target.files[0];
drawCroppedImage(file, 86, 86);
});
function drawCroppedImage(file, w, h) {
var canvas = document.getElementById('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
var image = new Image();
image.addEventListener('load', function (e) {
var sx = (image.width / 2) - (w / 2), // Source X
sy = (image.height / 2) - (h / 2), // Source Y
dx = 0, // Destination X
dy = 0; // Destination Y
ctx.drawImage(image, sx, sy, w, h, dx, dy, w, h);
});
image.src = URL.createObjectURL(file);
}
<input type="file" name="input">
<br><br>
<canvas id="canvas" width="86" height="86"></canvas>
I want to stretch the image to the size of the canvas. But the image takes its original size instead of taking the canvas size.Any help is appreciated.
var canvas = document.createElement("canvas");
canvas.setAttribute("width", "100px");
canvas.setAttribute("height", "180px");
//alert(canvas.height);
myImg.width = canvas.width;
myImg.height = canvas.height;
var ctx44 = canvas.getContext("2d");
ctx44.drawImage(myImg, 0, 0, canvas.width, canvas.height,0,0,canvas.width,canvas.height);
// image gets displayed in its original size instead of taking the size of the canvas
The 2nd ~ 4th parameters of drawImage represent the source rectangle. That is, a rectangle from where your image will be cropped, before being applied to the destination, resized by the rectangle defined in the following rectangle.
Here is a simple demo:
var img = new Image();
img.onload = e => {
const source = document.getElementById('source');
const destination = document.getElementById('destination');
const imgWIDTH = source.width = destination.width = 300;
const imgHEIGHT = source.height = destination.height = 300;
const src_x = source.getContext('2d');
const dest_x = destination.getContext('2d');
src_x.drawImage(img, 0, 0, imgWIDTH, imgHEIGHT); // simple copy to source canvas
const source_rect = {
x: 20,
y: 20,
w: 150,
h: 150
};
const dest_rect = {
x: 0,
y: 0,
w: 300,
h: 300
};
destination.getContext('2d')
.drawImage(source,
source_rect.x,
source_rect.y,
source_rect.w,
source_rect.h,
dest_rect.x,
dest_rect.y,
dest_rect.w,
dest_rect.h
);
// show the source rectangle on the 'source' canvas
src_x.strokeRect(
source_rect.x,
source_rect.y,
source_rect.w,
source_rect.h,
);
};
img.src = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"
<canvas id="source"></canvas>
<canvas id="destination"></canvas>
So in your case, if your original image is smaller than the 100x180px of your canvas, you are defining the source rectangle to be outside of the source image, this will then result in no apparent changes from the original image.
What you probably wanted was
ctx44.drawImage(myImg, 0, 0, myImg.naturalWidth, myImg.naturalHeight,0,0,canvas.width,canvas.height);
which is the same as the 5 param version
ctx44.drawImage(myImg,0,0,canvas.width,canvas.height);
var myImg = new Image();
myImg.onload = function(e) {
var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 180;
var ctx44 = canvas.getContext("2d");
ctx44.drawImage(myImg, 0,0,canvas.width,canvas.height);
document.body.appendChild(myImg);
document.body.appendChild(canvas);
};
myImg.src = "https://i.stack.imgur.com/LbM0l.jpg?s=32&g=1"
I need to create Canvas element with image and need to append to parent for this i have done this
<html>
<head>
<script>
window.onload = function() {
var canvas = document.createElement('canvas');
var context = canvas.getContext("2d");
canvas.id = "canvas_id";
canvas.setAttribute("class" ,"canvas");
canvas.height = "400";
canvas.width = "800";
var image = new Image();
image.src = "http://localhost/tile.png";
image.onload = function(){
context.drawImage(image, canvas.width, canvas.height);
}
document.body.appendChild(canvas);
}
</script>
</head>
<body>
</body>
</html>
it give blank canvas
can somebody guide me ?
You are using drawImage() the wrong way. Instead of drawing the image at (0,0) you are drawing it just outside the canvas area as width and height is where position normally goes.
The valid signatures are:
context.drawImage(image, dx, dy)
context.drawImage(image, dx, dy, dw, dh)
context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
Where dx and dy are delta position (relative to origin, normally (0,0) when untranslated). Without width and height specified drawImage() will by default use the image's natural width and height.
The second version allows to override the default size, and the third will allow you to draw from one region to another.
Source
Corrected example:
window.onload = function() {
var canvas = document.createElement('canvas');
var context = canvas.getContext("2d");
canvas.id = "canvas_id";
canvas.className = "canvas"; // should be className
canvas.height = 400; // should be numbers
canvas.width = 800;
var image = new Image();
image.onload = function() {
// or set canvas size = image, here: (this = currently loaded image)
// canvas.width = this.width;
// canvas.height = this.height;
context.drawImage(this, 0, 0); // draw at (0,0), size = image size
// or, if you want to fill the canvas independent on image size:
// context.drawImage(this, 0, 0, canvas.width, canvas.height);
}
// set src last (recommend to use relative paths where possible)
image.src = "http://lorempixel.com/output/fashion-q-c-800-400-7.jpg";
document.body.appendChild(canvas);
}
That being said, if you only need the image appended there is no need to go via canvas. Just add the image to DOM directly (I assume this is not you want, but just in case..):
var image = new Image();
image.src = "tile.png";
document.body.appendChild(image);
This is my take on it... You need to indicate the coordinates where you want to start drawing (i.e. 0, 0) and - optionally - you can specify how big (wide, height) the canvas is to be.
In my case, I make the canvas to be as big as the image (instead of an arbitrary 400x800) you may need to update that your suit your requirements.
I added some css to show how big the canvas is in relation to the image. You can update/remove that as well depending on your needs.
UPDATED
It uses an hidden image as the source.
I hope this will work for you.
window.onload = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
canvas.id = 'canvas_id';
canvas.setAttribute("class", "canvas");
var image = new Image();
image.src = 'http://placekitten.com/g/200/300';
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, image.width, image.height);
document.body.appendChild(canvas);
}
.canvas {
border: solid red 1px;
}
<html>
<body>
</body>
</html>
I am trying to draw an image from binary string on to the canvas.
var reader = new FileReader();
//reader.readAsDataURL(file);
reader.readAsBinaryString(file);
reader.onload = function(event){
var d = $(thisObj.CreateIndoorFormDivControlName).dialog();
var canvas =document.getElementById('canvasfloorLayout');
var cxt=canvas.getContext("2d");
var img=new Image();
img.onload = function() {
cxt.drawImage(img, 0, 0,canvas.width,canvas.height);
}
img.src = "data:image/jpeg;base64,"+window.btoa(reader.result);
I am using the above code but the problem is the image size is getting reduced to the canvas size and quality is dropping like anything. I have been tried with
cxt.drawImage(img, 0, 0,img.width,img.height);
But the image gets cropped.
I donot want to use reader.readAsDataURL as I need to post the binary to the server. My requirement is to show the full image and draw lines on it .
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
...if you draw the image at the canvas' native resolution, then when the image gets scaled, it's obviously going to lose quality.
...if you draw the image at the image's native resolution, but the canvas hasn't changed size, then you're going to end up with a partial image, or a partially-filled canvas.
So if you want neither of those, then set the dimensions of the canvas to match the dimensions of the image, and you'll have a canvas-drawn image which matches the resolution of the data-image.
EDIT
Adding an example of a proxy, between the two.
var img = new Image(),
canvas = document.createElement("canvas"),
context = canvas.getContext("2d"),
// ......etc
dimensions = {
max_height : 800,
max_width : 600,
width : 800, // this will change
height : 600, // this will change
largest_property : function () {
return this.height > this.width ? "height" : "width";
},
read_dimensions : function (img) {
this.width = img.width;
this.height = img.height;
return this;
},
scaling_factor : function (original, computed) {
return computed / original;
},
scale_to_fit : function () {
var x_factor = this.scaling_factor(this.width, this.max_width),
y_factor = this.scaling_factor(this.height, this.max_height),
largest_factor = Math.min(x_factor, y_factor);
this.width *= largest_factor;
this.height *= largest_factor;
}
};
dimensions.read_dimensions(img).scale_to_fit();
canvas.width = dimensions.width;
canvas.height = dimensions.height;
context.drawImage(img, 0, 0, dimensions.width, dimensions.height);