Dynamically adding image source - javascript

I have problems regarding printing an image and adding the image source. I have to do it dynamically. I need a random number from 0 to 9 generated and use that number to show that image. I have 10 images
(number0.jpg, number1.jpg, number2.jpg…).
The code is this:
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="258" height="187"></canvas>
<script>
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var whichImg;
var randNum;
var img = new Image();
img.onload = function(){
randNum = Math.floor(Math.random() * 10);
can.width = img.width;
can.height = img.height;
whichImg="number" + randNum + ".jpg" ;
ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = whichImg; //having problems with this row
</script>
</body>
</html>
The last line doesn’t work. If I call that as is
img.src = “number1.jpg”,
it shows the image. This way it doesn’t. What can I do to show the image?
Thanks

You need to populate whichImg right after initializing it:
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var whichImg;
var randNum;
randNum = Math.floor(Math.random() * 10);
whichImg="number" + randNum + ".jpg" ;
var img = new Image();
img.onload = function(){
randNum = Math.floor(Math.random() * 10);
can.width = img.width;
can.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = whichImg; //having problems with this row

Related

drawImage resize image to 500px high

I am trying to take the image that is 1280x960 and resize it using drawImage so that is is 600 pixels high. I have worked out the ratio that I think I need to achieve this but don't know how to apply...
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
canvas.height = this.height;
canvas.width = this.width;
ratio = canvas.height / canvas.width;
console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);
ctx.drawImage(img, 0, 0, 300, 500);
}
img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
<canvas id="mycanvas"></canvas>
How can I specify the resulting image size, making the width automatic? I eventually want this function to resize any image to 500 pixels high.
Here is a solution, a bit roundabout but seems to work. I created a new image using toDataURL() from the original sized canvas. Although the new image is reduced, the total dimension is still that of the original image, such that the remaining space is transparent. Then I set and clip this image into a new canvas. The resulting canvas has the correctly sized image which can be copied and pasted with the desired dimension.
If the snippet below does not display the image in the new canvas, please try the following fiddle which seems to work well: https://jsfiddle.net/jfeferman/u80fhy0z/
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.crossOrigin = "Anonymous";
img.onload = function () {
canvas.height = this.height;
canvas.width = this.width;
ratio = canvas.height / canvas.width;
console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);
ctx.drawImage(img, 0, 0, 500 / ratio, 500);
var newImage = new Image();
newImage.crossOrigin = "Anonymous";
newImage.src = canvas.toDataURL();
var newCanvas = document.getElementById("newcanvas");
newCanvas.height = 500;
newCanvas.width = 500 / ratio;
var newCtx = newCanvas.getContext('2d');
newCtx.drawImage(newImage, 0, 0, 500 / ratio, 500, 0, 0, 500 / ratio, 500);
}
img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
#mycanvas {
display: none;
}
<canvas id="newcanvas"></canvas>
<canvas id="mycanvas"></canvas>
I applied the ratio to your call to drawImage and it seems to work:
ctx.drawImage(img, 0, 0, 500 / ratio, 500);
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
canvas.height = this.height;
canvas.width = this.width;
ratio = canvas.height / canvas.width;
console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);
ctx.drawImage(img, 0, 0);
canvas.style.width = 500 / ratio + "px";
canvas.style.height = 500 + "px";
}
img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
<canvas id="mycanvas"></canvas>

HTML 5 Canvas image overlay repeatable

I am trying to take a pattern and apply it over a png image but only cover the non-transparent part of the image similar to this one.
http://jsfiddle.net/eLmmA/1/
$(function() {
var canvas = document.createElement('canvas');
canvas.width = 250;
canvas.height = 250;
var canvas_context = canvas.getContext("2d");
var img = new Image();
img.onload = function(){
var msk = new Image();
msk.onload = function(){
canvas_context.drawImage(img, 0, 0);
canvas_context.globalCompositeOperation = "destination-in";
canvas_context.drawImage(msk, 0, 0);
canvas_context.globalCompositeOperation = "source-over";
};
msk.src = 'http://i.stack.imgur.com/QtQrZ.png';
}
img.src = 'http://i.stack.imgur.com/MDGFY.jpg';
document.body.appendChild(canvas);
});
The example above is really close to what I want but I need to be able to use a smaller texture image and repeat it over the none pattern image. I am not familiar with how to use canvas properly but trying to learn more about it.
Thanks in advance!
Never mind I figured it out.
var canvas = document.createElement('canvas');
canvas.width = 250;
canvas.height = 250;
var canvas_context = canvas.getContext("2d");
var img = new Image();
img.onload = function(){
var msk = new Image();
msk.onload = function(){
var ptrn = canvas_context.createPattern(img, 'repeat');
canvas_context.fillStyle = ptrn;
canvas_context.fillRect(0, 0, canvas.width, canvas.height);
canvas_context.drawImage(img, 0, 0);
canvas_context.globalCompositeOperation = "destination-in";
canvas_context.drawImage(msk, 0, 0);
canvas_context.globalCompositeOperation = "source-over";
};
msk.src = $('#base_url').data('base')+'assets/themes/img/download.png';
}
img.src = $('#base_url').data('base')+'assets/uploads/thumbs/1381413411Purple-Night-Owls-thumb.jpg';
$('#itemPreview').html(canvas);

HTML Canvas Images - Drawing multi canvas image in a page

i have a problem with canvas.
i can draw a canvas with single image, but i can't draw each canvas with image separate.
- if data just have one image it's working fine, but data have multiple image it's not working
can you help me ?
<script>
var h_notepad = 500;
var w_notepad = 737;
var data = [
{dataImageURL: "1_sat_1.png"},
{dataImageURL: "1_sat_2.png"},
{dataImageURL: "1_sat_3.png"},
{dataImageURL: "1_sat_4.png"}
];
for(var i = 0; i < data.length ; i++){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
canvas.width = w_notepad;
canvas.height = h_notepad;
img.crossOrigin = 'anonymous';
img.width = w_notepad;
img.height = h_notepad;
console.log(img);
img.onload = function(){
ctx.drawImage(img, 0, 0, w_notepad, h_notepad);
};
img.src = data[i].dataImageURL;
$('body').append(canvas);
}
</script>
<html>
<head>
<meta charset="utf-8">
<title>DRAWING</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<meta charset="utf-8">
</head>
<body>
</body>
</html>
I guess you only get the last one.
It's a closure problem.
When the load event fires, img and ctx only refer to the last ones created.
So you draw data.length time on the same canvas.
To avoid it, you can use this and wrap the canvas creation in the onload handler:
var imgs = ['http://lorempixel.com/200/300/', 'http://lorempixel.com/500/300/', 'http://lorempixel.com/200/100/'];
for (var i = 0; i < imgs.length; i++) {
var img = new Image();
var width = 500;
var height = 300;
img.onload = function() {
var c = document.createElement('canvas');
c.width = width;
c.height = height;
document.body.appendChild(c);
var ctx = c.getContext('2d');
ctx.drawImage(this, 0,0, width, height);
};
img.src = imgs[i];
}
Problem is that onload is asynchronous. So all your code runs before any of onload functions will be called. That is why your function
img.onload = function(){
ctx.drawImage(img, 0, 0, w_notepad, h_notepad);
};
uses the latest ctx and renders all images in this context.
What you can do is cover this asynchronous call with a synchronous function scope:
(function(ctx, img, w_notepad, h_notepad) {
img.onload = function(){
ctx.drawImage(img, 0, 0, w_notepad, h_notepad);
};
})(ctx, img, w_notepad, h_notepad);
This isolates the variables and keeps there values until you receive the image.

How to stretch image in canvas?

I need to stretch my image to the top and to the bottom in canvas.
How can I do this?
Here's the codepen
HTML
<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;">
</canvas>
JS
window.onload = function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;
img.src = "http://www.w3schools.com/tags/img_the_scream.jpg"
ctx.drawImage(img, 10, 10);
}
drawImage allows you to pass the width and height as third and fourth parameter.
So your last line should be ctx.drawImage(img, 0, 0,c.width, c.height); in order to fill the entire canvas.
If you just want an image to stretch to fill in the height you can do something like this jsFiddle : https://jsfiddle.net/CanvasCode/92ekrbnz/
javascript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;
ctx.fillStyle = "#000";
ctx.fillRect(0,0,c.width,c.height);
img.src = "http://www.w3schools.com/tags/img_the_scream.jpg"
img.onload = function () {
ctx.drawImage(img, (c.width / 2) - (img.width / 2), 0, img.width, c.height);
}
However the link you provided basically just zooms into the image.
So you can do something like this jsFiddle : https://jsfiddle.net/CanvasCode/92ekrbnz/2/
javascript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;
var zoom = 1.0;
img.src = "http://www.w3schools.com/tags/img_the_scream.jpg"
setInterval(function () {
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, c.width, c.height);
ctx.drawImage(img, (c.width / 2) - ((img.width * zoom) / 2), (c.height / 2) - ((img.height * zoom) / 2),
img.width * zoom,
img.height * zoom);
}, 1);
document.getElementById("zoomIn").onclick = function () {
zoom += 0.1;
};
document.getElementById("zoomOut").onclick = function () {
if (zoom > 0.1) {
zoom -= 0.1;
}
};
Here is a more detailed answer of how to fill or fit a canvas while also keeping the image aspect.
Fill canvas

Image Conversion wrongly cropping

In my application i have added the code to convert the image into base 64 with a resized images.When i try the following code the image part has been cropped.
function getBase64FromImageUrl(URL)
{
var img = new Image();
img.style.width = this.width,
img.style.height = this.height,
img.src = URL;
img.onload = function ()
{
var canvas = document.createElement("canvas");
canvas.width =150
canvas.height =150;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 10, 10);
var dataURL = canvas.toDataURL("image/jpg");
c=dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
return c;
}
}
How to get the full image properly?What change requires in the code
function encodeImage(src, callback) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
callback(canvas.toDataURL());
}
img.src = src;
}
See this fiddle:
http://jsfiddle.net/NwaPT/3/

Categories

Resources