HTML canvas image is not showing - javascript

This is the code:
<head>
<title>Canvas</title>
</head>
<body>
<canvas id="c" width="200" height="200">
</canvas>
<script>
var c = document.querySelector("#c");
var ctx = c.getContext("2d");
var image = new Image();
image.onLoad = function() {
console.log("Loaded Image");
ctx.drawImage(image, 0, 0, c.width, c.height);
};
image.src = "fry_fixed.jpg";
</script>
</body>
Canvas is getting created.
Image is not appearing.
I tried to debug it and found that the onLoad function is not working.
I can ensure you that image is in the same folder and the image name is correct.
But i still can't figure out why the code is not working!!

case matters, it's onload, all lowercase, not onLoad
image.onload = function() {...
or the more modern addEventListener
image.addEventListener('load', function() {...}, false);

Use onload instead of onLoad. Or even better, use an event listener!
var c = document.querySelector("#c");
var ctx = c.getContext("2d");
var image = new Image();
// Better use addEventListener, to be honest.
// image.onload = function() {
// ctx.drawImage(image, 0, 0, c.width, c.height);
// };
image.addEventListener('load', function(){
ctx.drawImage(image, 0, 0, c.width, c.height);
}, false)
image.src = "http://placehold.it/200x200";
<canvas id="c" width="200" height="200"></canvas>

Related

dataURL not working when the context of the canvas is an image

i was trying to download the context of the canvas as an image using dataURL() through the following code but it's not working for some reason. However, when i replace the context of the canvas to be something else besides the image it actually works, so can you tell how can i fix this
<a href="#" id="downloader" >Download!</a>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var image = new Image(60, 45);
image.onload = function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
ctx.drawImage(image, 0, -60);
}
image.src = 'image.png';
$('#downloader').click(function(){
$(this).attr('href', document.getElementById('canvas').toDataURL("image/png").replace("image/png", "image/octet-stream"));
$(this).attr('download', "Picture.png");
});
</script>
Your JS should be:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var image = new Image(60, 45);
//First add src, then set the height and width
image.src = 'image.png';
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
// Draw image from start and not from behind the axis
ctx.drawImage(image, 0, 0);
}
$('#downloader').click(function() {
$(this).attr('href', document.getElementById('canvas').toDataURL("image/png"))
$(this).attr('download', "Picture.png");
});

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.

Auto refresh html canvas image not working

For my website, I need to redraw an image from server which is continuously updating. I found the solution and tried but it still does not auto refresh. I also tried adding a dummy string to my image(local0.jpg) so that the browser does not use cached image but no success. What am I doing wrong?
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<canvas id="canvas" width="400" height="400"> </canvas>
<script>
var imageObj=new Image();
imageObj.src="local0.jpg?dummy=8484744"
imageObj.onload=function()
{
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.drawImage(imageObj,0, 0,canvas.width,canvas.height);
setTimeout(timedRefresh,1000);
}
function timedRefresh()
{
imageObj.src = "local0.jpg?dummy=8484749"
}
</script>
</body>
</html>
Try the following code
var imageObj = new Image();
imageObj.onload = function() {
drawOnCanvas();
setTimeout(timedRefresh, 1000);
}
// set src AFTER assigning load
imageObj.src = "local0.jpg?dummy=" + Math.random();
function timedRefresh() {
imageObj.src = "local0.jpg?dummy=" + Math.random();
//drawOnCanvas(); //flicker was due this line as it try to draw image load so i commented it... now it should work...
}
function drawOnCanvas() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(imageObj, 0, 0, canvas.width, canvas.height);
}
your function timedRefresh add random values to image
function timedRefresh()
{
imageObj.src = "local0.jpg?dummy=" + Math.floor((Math.random() * 10000) + 1);
}

'Tainted canvases may not be exported' when using drawImage [duplicate]

This question already has an answer here:
Canvas image crossplatform insecure error
(1 answer)
Closed 7 years ago.
When trying to draw an image onto a canvas, and then saving the canvas to an image, I get the following error:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported
var picture = new Image();
picture.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/800px-Smiley.svg.png";
var canvas = document.getElementById("background");
var context = canvas.getContext("2d");
function generate(){
var ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = canvas.width;
ctx.canvas.height = canvas.height;
ctx.fillStyle = "red";
ctx.rect (0, 0, 40, 40);
ctx.fill();
ctx.drawImage(picture,0,0);
image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.src = ctx.canvas.toDataURL("image/png");
}
function draw(){
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0,0,100,100,0,0,100,100);
}
function play(){
generate();
setInterval(function(){draw();}, 0.0333);
}
window.onload = function(){
if(picture.complete)play();
else picture.onload = play;
}
<canvas id="background" width=500 height=500></canvas>
I know it's to do with drawing the image on the canvas because when that line is removed everything's okay and you can see the red box:
var picture = new Image();
picture.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/800px-Smiley.svg.png";
var canvas = document.getElementById("background");
var context = canvas.getContext("2d");
function generate(){
var ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = canvas.width;
ctx.canvas.height = canvas.height;
ctx.fillStyle = "red";
ctx.rect (0, 0, 40, 40);
ctx.fill();
image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.src = ctx.canvas.toDataURL("image/png");
}
function draw(){
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0,0,100,100,0,0,100,100);
}
function play(){
generate();
setInterval(function(){draw();}, 0.0333);
}
window.onload = function(){
if(picture.complete)play();
else picture.onload = play;
}
<canvas id="background" width=500 height=500></canvas>
So it's drawImage that causes this to fail.
I've read other questions and the solutions were "just add image.setAttribute('crossOrigin', 'anonymous');" (which I've done) or to put them in the same directory (I tried this by placing both files on desktop) but neither seemed to solve it for me.
Is there a fix or an alternative method? All I want to do is draw multiple images onto one image. (The red box was just for show.)
I tried this by placing both files on desktop
No. You need a web server and to open your files in http:// (or https://) for them to be considered of the same origin. When you open your files in file://, they're not considered of the same origin, even if you serve them from the same directory.

Lasso tool in html5 canvas

I'm trying to build a freeform lasso tool to clip an image inside canvas. I'm using fabric.js to draw the shape.
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function() {
var OwnCanv = new fabric.Canvas('c', {
isDrawingMode: true
});
OwnCanv.freeDrawingBrush.color = "purple"
OwnCanv.freeDrawingBrush.width = 4
ctx.clip();
ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<canvas id="c" width="500" height="500"></canvas>
This is my attempt which doesn't seem to work, what am I doing wrong here ?
Can anyone help me please? It would really be appreciated.
The image needs to be a fabric.Image.
You could try something like this:
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function() {
var OwnCanv = new fabric.Canvas('c', {
isDrawingMode: true
});
var imgInstance = new fabric.Image(img, {
left: 0,
top: 0,
});
OwnCanv.add(imgInstance);
OwnCanv.freeDrawingBrush.color = "purple"
OwnCanv.freeDrawingBrush.width = 4
OwnCanv.on('path:created', function(options) {
var path = options.path;
OwnCanv.isDrawingMode = false;
OwnCanv.remove(imgInstance);
OwnCanv.remove(path);
OwnCanv.clipTo = function(ctx) {
path.render(ctx);
};
OwnCanv.add(imgInstance);
});
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<canvas id="c" width="500" height="500"></canvas>
See these resources for more:
http://fabricjs.com/fabric-intro-part-1/
Multiple clipping areas on Fabric.js canvas
Fabric.js Clip Canvas (or object group) To Polygon

Categories