How to draw existing <img> to canvas - javascript

I know I can do this using javascript:
var ctx = getCanvas('testCanvas').getContext('2d'); // get Canvas context
var img = new Image();
img.src = 'test.png';
img.onload = function(){
ctx.drawImage(img, 200, 200); // x, y, width, height
}
But how to draw existing tag to canvas:
In html:
<img src='test.png'>
Why I want to do this? I want to optimize image loading using pagespeed

The very first google hit for your question is promising:
var c=document.getElementById("testCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("existingHTMLImageElementId");
ctx.drawImage(img,10,10);
See w3Schools

Try
var canvas=document.getElementById("test");
var ctx=canvas.getContext("2d");
var img=document.getElementById("imgID");
ctx.drawImage(img,10,10);

assuming that your has the id #image, you could use
var img = document.getElementById("image");
var ctx = getCanvas('testCanvas').getContext('2d'); // get Canvas context
img.onload = function(){
ctx.drawImage(img, 200, 200); // x, y, width, height
}

Suppose you have an <img> tag with id of image. You can obtain the image reference by using the getElementById method. Something like the following:
var img = document.getElementById("image");
Then using your code above.

You can give the image src to your new image
var ctx = getCanvas('testCanvas').getContext('2d'); // get Canvas context
var img = new Image();
img.src = document.getElementById('testImage').src;
img.onload = function(){
ctx.drawImage(img, 200, 200); // x, y, width, height
}
add id to your image element
<img src='test.png' id="testImage">

Related

HTML canvas not drawing image from file

I am trying to load an image from a file and draw it on a canvas. I have this..
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
myImage = new Image();
myImage.src = "img/image.jpg";
context.drawImage(myImage, 0, 0, 100, 100);
This is not drawing anything on the screen, where am I going wrong? I can see the image being loaded by developer tools so I know that it can find the file itself.
If the canvas element is already on the page, you'll need to replace the createElement method with querySelector:
// const canvas = document.createElement("canvas");
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
myImage = new Image();
myImage.src = "img/image.jpg";
myImage.addEventListener("load", ()=>{
context.drawImage(myImage, 0, 0, 100, 100);
}); // Thanks to Xion 14 for the reminder!
Otherwise, you'll need to append the canvas element to the DOM, e.g. via document.body.appendChild( canvas );

Replace Rectangle on Canvas with Image

I'm building a simple video game using HTML Canvas and JavaScript. I'm trying to replace a black square with an image of a strawberry, but the image is not displaying on the canvas. How would I make the image replace the square?
this.draw = function() {
var img = new Image();
img.src = "strawberry.png";
ctx.drawImage(img, 10, 10);
ctx.fillStyle = "black";
ctx.fillRect(this.x, this.y, 10, 10);
}
The problem is that the image may not have loaded by the time the code is being called. You will need to wait for that to happen.
Try:
function loadimage() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image();
img.src = "strawberry.png";
img.onload = function() {
ctx.drawImage(img, 0, 0, c.width, c.height);
}
}
window.onload = loadimage;
I have put a version of this code (I have a different image filename for my test) into a SCRIPT tag in the HEAD section of the page. The code runs when the page has finished loading, but the code itself waits for the img.onload event to be triggered before actually drawing the image. And, change "myCanvas" to the ID of your canvass tag.

Can't get base64 resized image from javascript canvas

I have two main questions. I'm trying to resize a base64 image according to the answer in
JavaScript reduce the size and quality of image with based64 encoded code
This seemed simple enough, except for the fact that I need to get only the base64 string from that function, without the data:image... header.
I tried to modify the function like this:
function resizeBase64Img(base64, width, height) {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
var deferred = $.Deferred();
$("<img/>").attr("src", "data:image/gif;base64," + base64).load(function () {
context.scale(width / this.width, height / this.height);
context.drawImage(this, 0, 0);
deferred.resolve($("<img/>").attr("src", canvas.toDataURL()));
});
var result = canvas.toDataURL();
return result.substr(result.indexOf(",") + 1)
}
which returns a base64 string. This string is corrupted, and it never displays correctly. Why is this happening and how can I fix it?
The other question is, is there a way to resize the image based on percentage and not on pixel size?
Thanks
I ended up rewriting the function based on another canvas function I found. This function takes the src of a base64 img, modifies the size and assigns the result in base64 to another element:
function resizeBase64Img(url, width, height) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.scale(width/this.width, height/this.height);
ctx.drawImage(this, 0, 0);
result=canvas.toDataURL();
$('#ASSIGNEDELEMENT').val(result.substr(result.indexOf(",") + 1));
};
img.src = url;
}
And it should be invoked like this:
resizeBase64Img($('#image').attr('src'),300,300);

Javascript How to change height and width of an image src

I'm trying to do something very simple. I want to take an image from a document. Draw it to the screen. And be able to resize this image's height and width to what ever I choose.
What I have now doesn't change the size at all.
What am I doing wrong? I don't want to use anything but Javascript for this.
var ctx = document.getElementById('mycanvas').getContext('2d');
var img = new Image();
function draw(){
img.onload = function(){
ctx.drawImage(img,100,100);
};
img.style.height = '300px';
img.style.width = '300px';
img.src = "test.png";
}
draw();
context.drawImage has additional arguments that do the resizing for you:
var img=new Image();
img.onload=function(){
var scaleFactor=2.00;
ctx.drawImage(
img,
100,100,
img.width*scaleFactor,img.height*scaleFactor
);
}
img.src='test.png'

Canvas drawImage() not working

This Javascript code draw part of the image on the canvas:
var img = document.getElementById('img');
var canvas = document.getElementById('can');
//canvas.width = img.width;
//canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
But when I uncomment the middle lines to set the canvas width and height, the drawImage() does not work.
What should I check in order to find the problem?
You need to wait for the browser to load the image.
Use onload event if image was not yet loaded and change your code to something like this:
var img = document.getElementById('img');
var canvas = document.getElementById('can');
var ctx = canvas.getContext("2d");
var callback = function(image) {
if(!image) image = this;
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(image, 0, 0);
}
if(img.complete) { //check if image was already loaded by the browser
callback(img);
}else {
img.onload = callback;
}
See this working demo
var img = document.getElementById('img');
Try naming the variable something else. Also make sure some image is loaded.
Try my fiddle http://jsfiddle.net/aliasm2k/tAum2/ for more ideas
The width and height image attributes aren't set until the image is loaded, so i propose you to put your code in onLoad() image event.

Categories