I try to build a javascript code, to draw a image on canvas, but I don't know where go wrong.
That is my code:
<body>
<canvas id = "my_canvas"></canvas>
<script>
function setup(){
var canvas = document.getElementById('my_canvas');
var ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
var image = new Image();
image.src = 'a.png';
ctx.drawImage(image,5,5);
};
window.onload = setup;
setup();
</script>
The question is, if I put a line of code setup(); at end then the image is correctly draw, I don't know why.
Thanks.
The problem is that image is loaded asynchronously, so if you set the source and draw it immediately then the image bits are not yet available and nothing is drawn.
You have to wait for the image to load before being able to draw it on a canvas.
Changing the code to
image.onload = function() {
ctx.drawImage(image, 5, 5);
};
image.src = "a.png";
should work as expected.
The image is loading asynchronously. This code will work:
JavaScript:
function setup(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
var image = new Image();
image.onload = function () {
ctx.drawImage(image,5,5);
};
image.src = 'a.png';
}
window.onload = setup;
Related
I've read a bunch of topics here about this but I can't figure out what my problem is.
I have this :
function init() {
canvas = document.getElementById("Canvas");
canvas.width = document.body.clientWidth;
canvas.height = window.innerHeight-30;
var stage = new createjs.Stage(canvas);
createjs.Ticker.addEventListener("tick", tick);
createjs.Ticker.framerate = 65;
var image = new Image();
image.src = "Pics/tipeee-logo-pointcom-RVB.png";
image.onload = function(){
var bitmap = new createjs.Bitmap(image);
stage.addChild(bitmap)
;};
}
function tick(event){
init();
stage.update();
}
There's more code within the functions, but nothing to do with the image, and no image is dispayed.
Can you help me ?
Thanks !
I want to get an image scaled correctly after loading it with a dummy click on a <input type='file'> and compressing it via drawing it onto a canvas. When calling a console.log() inside the img.onload I discovered it was being run in a loop. Putting the img.src = canvas.toDataURL("image/png") outside of the onload results in a blank image but no loop. Moving things around by trial and error has not been effective as I don't get the dynamics at play here (even though I can get images redrawn when rescaling a canvas). Thanks!
$('button.picture').on('click',function(){
var outerWrapper = $(this).closest('.outerWrapper')
$(this).siblings('.imageLoad').on('change', function(e){
var loadedImage = e.target.files[0]
var img = new Image();
img.src = window.URL.createObjectURL(loadedImage);
var canvas = document.createElement("canvas");
canvas.width = outerWrapper.width()
canvas.height = outerWrapper.height()
img.onload = function(e){
//still here the img.width returns the canvas width and not the original image's width
console.log(img.width)
var context = canvas.getContext("2d");
context.drawImage(img,0,0, canvas.width, canvas.height )
img.src = canvas.toDataURL("image/png")
}
$(this).closest('.outerWrapper').children('.imageWrapper').append(img)
})
$(this).siblings('.imageLoad').trigger('click')
})
To answer my own question I want to make clear what my aims were:
Load in image through a dummy click on an <input type="file">
Keeps the aspect ratio of the original image
Compress it
What worked was not setting img.src = canvas.toDataURL("image/png") as you would when resizing a canvas but by loading the original again image with URL.createObjectURL(loadedImage). To preserve the aspect ration I had to create two separate images, one to get the img.naturalWidth and img.naturalHeight for calculation and the next to load the image onto the canvas. Works a charm. Would be interested to learn where it can be refined.
$('button.picture').on('click',function(){
var outerWrapper = $(this).closest('.outerWrapper')
$(this).siblings('.imageLoad').on('change', function(e){
var loadedImage = e.target.files[0]
var img = new Image();
img.src = window.URL.createObjectURL(loadedImage);
var canvasPic = $('<canvas class="canvasPic"></canvas>')
canvasPic.prependTo(outerWrapper)
var canvas = canvasPic[0]
canvas.width = outerWrapper.width()
canvas.height = outerWrapper.height()
var context = canvas.getContext("2d");
var image = new Image();
image.onload = function(){
var w = img.naturalWidth
var h = img.naturalHeight
var ratio = h/w
var newWidth = canvas.height/ratio
context.drawImage(img,0,0,newWidth,canvas.height)
}
image.src = URL.createObjectURL(loadedImage);
})
$(this).siblings('.imageLoad').trigger('click')
})
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id="spriteCanvas" width="500" height="500">
<img id="coin" width="440" height="40" src="coin.png">
</canvas>
</body>
</html>
I tried placing an image inside a canvas element, but it won't display on the browser. I know the image tag works because it's displayed if I place it outside of the canvas element. Also, if I inspect the canvas element, I can see that the image is inside, but its dimensions are 0 by 0. Can somebody explain why this isn't working?
EDIT: My original code added the image through javascript, but it wouldn't show on the canvas. It was giving me the same problems as above. But I just realized I was missing "onload".
original code:
var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');
function Sprite(canvas, width, height, image){
this.context = canvas.getContext("2d");
this.width = width;
this.height = height;
this.image = image;
}
Sprite.prototype.render = function() {
var that = this;
this.context.drawImage(that.image, 0, 0);
}
function init() {
var coin = new Sprite(sCanvas, 100, 100, coinImage);
coin.render();
}
init();
editted code:
var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');
function Sprite(canvas, width, height, image){
this.context = canvas.getContext("2d");
this.width = width;
this.height = height;
this.image = image;
}
Sprite.prototype.render = function() {
var that = this;
this.context.drawImage(that.image, 0, 0);
}
coinImage.onload = function () {
var coin = new Sprite(sCanvas, 100, 100, coinImage);
coin.render();
}
This isn't how a <canvas> tag works. If you want your image to appear in your canvas, you will have to use JavaScript to place the pixels of the image into your canvas.
<canvas>s are exactly what they state: canvases. They are an element for you to draw on programmatically. If you just want to display an image on a page, you don't need a canvas, you just need the <img> tag. In fact, elements should not be placed in <canvas>.
Take a look at CanvasRenderingContext2D.drawImage() and this tutorial: HTML5 Canvas Image Tutorial.
And this snippet:
var canvas = document.getElementById("painting"),
ctx = canvas.getContext("2d"),
image = new Image();
image.onload = function() {
ctx.drawImage(image, 30, 50);
};
image.src = "http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.png?v=10a9e8743fb0";
<canvas id="painting" width="300" height="300"></canvas>
To draw an image on a canvas, use the following method:
drawImage(image,x,y)
If the image you want to draw is not in the DOM already you can load an image directly from a URL with a few lines of javascript.
function loadAndDrawImage(url)
{
// Create an image object. This is not attached to the DOM and is not part of the page.
var image = new Image();
// When the image has loaded, draw it to the canvas
image.onload = function()
{
// draw image...
}
// Now set the source of the image that we want to load
image.src = url;
}
loadAndDrawImage("http://www---.png");
I try to build a javascript code, to draw a image on canvas, but I don't know where go wrong.
That is my code:
<body>
<canvas id = "my_canvas"></canvas>
<script>
function setup(){
var canvas = document.getElementById('my_canvas');
var ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
var image = new Image();
image.src = 'a.png';
ctx.drawImage(image,5,5);
};
window.onload = setup;
setup();
</script>
The question is, if I put a line of code setup(); at end then the image is correctly draw, I don't know why.
Thanks.
The problem is that image is loaded asynchronously, so if you set the source and draw it immediately then the image bits are not yet available and nothing is drawn.
You have to wait for the image to load before being able to draw it on a canvas.
Changing the code to
image.onload = function() {
ctx.drawImage(image, 5, 5);
};
image.src = "a.png";
should work as expected.
The image is loading asynchronously. This code will work:
JavaScript:
function setup(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
var image = new Image();
image.onload = function () {
ctx.drawImage(image,5,5);
};
image.src = 'a.png';
}
window.onload = setup;
I'm attempting to pull an image (in this case, /camera/frame, which is a known-good JPG), and load it as the background of my document.body.
Here's my code thus far:
var backgroundImage = new Image();
backgroundImage.onload = function ()
{
console.log("onload");
document.body.style.backgroundImage = this.src;
};
backgroundImage.src = 'camera/frame';
"onload" prints as expected, and this.src prints out the full URL to /camera/frame, however document.body.style.backgroundImage remains "".
I believe you may be missing two things.
var path = 'path/to/image.jpg';
document.body.style.background='url('+path+')';
Canvas 2D to the rescue!
var backgroundImage = new Image();
backgroundImage.onload = function ()
{
var canvas = document.getElementById('canvas');
canvas.width = this.width;
canvas.height = this.height;
var canvasContext = canvas.getContext('2d');
canvasContext.drawImage(this, 0, 0, this.width, this.height);
};
backgroundImage.src = 'camera/frame';
backgroundImage.width = $(window).width();
backgroundImage.height = $(window).height();
Loads the image in the background, then draws it into the canvas seamlessly!