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.
Related
I'm trying to have a page where users can customize a canvas and then email the finished project to themselves. I set the background of the canvas using the following javascript:
function setbackground1() {
document.getElementById('myCanvas').setAttribute("class",
"background1");
}
function setbackground2() {
document.getElementById('myCanvas').setAttribute("class",
"background2");
}
and included a form on the page to populate the rest of the canvas. I have tried various ways of including canvas.toDataURL() in order to save the canvas as an image that can later be emailed to them however the background image is not part of the saved image. (similar problem to Canvas to Save Image and Email but my text saves not my images)
I've been trying variations of this but it's not working for me.
function setbackground11() {
var img = new Image();
img.src = 'background1.jpg';
img.onload = function () {
ctx.fillRect( 0, 0, canvas.width, canvas.height )
}
}
I believe that I somehow have to reference myCanvas id as well
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');`
CSS styles aren't part of the canvas image. For a solid color:
ctx.fillStyle = 'green'
ctx.fillRect( 0, 0, canvas.width, canvas.height )
For an image:
var img = new Image();
img.src = 'background1.jpg';
img.onload = function () {
ctx.drawImage( img, 0, 0, canvas.width, canvas.height )
// do the rest of your drawing over the background
}
I have a problem loading an image to a canvas from a file (image) input. The fileInput object is the image picker. This is all one block JS file on my site:
<script>
function picEditor() {
var fileInput = document.createElement("input");
fileInput.setAttribute("type", "file");
fileInput.setAttribute("accept", "image/png");
fileInput.setAttribute("id", "fluff");
document.body.appendChild(fileInput);
Second part, the image is created. The image and load button are created first. The button's click function is supposed to set the source of the image to that of the file input's blob URL, then draw the image on the canvas.
var img = document.createElement("img");
var loadButton = document.createElement("button");
loadButton.onclick = function() {
img.src = window.URL.createObjectURL(fileInput.files[0]);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
};
loadButton.innerHTML = "Click here";
document.body.appendChild(loadButton);
Third part, the canvas and rendering context are created.
var canvas = document.createElement("canvas");
canvas.style.position = "absolute";
canvas.style.left = "740px";
canvas.style.top = "15px";
canvas.style.border = "1px #fa0 solid";
canvas.width = 600;
canvas.height = 600;
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
}
window.onload = picEditor();
</script>
My three visible objects are getting drawn, but the image isn't getting drawn when an image has been inputted and the load button has been clicked.
You have to wait till the image is ready before drawing it on the canvas
loadButton.onclick = function() {
img.onload = function() {
ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
};
img.src = window.URL.createObjectURL(fileInput.files[0]);
};
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.
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">
I make an application canvas. Every time I call draw () function, multiple images are drawn in canvas. The problem is that with Opera it does not work. Onload function does not always work.
function draw(){
ctx.clearRect (0, 0, canvas.width, canvas.height);
var img = new Image();
img.src = srcvolets;
img.onload = function(){
ctx.drawImage(img, 0, 0,canvas.width,canvas.height);
if(srccouleur!=null){
var img2 = new Image();
img2.src = 'images/couleurs/'+volets+'/'+srccouleur+'.png';
img2.onload = function(){
ctx.drawImage(img2, 0, 0,canvas.width,canvas.height);
if(srcsculpture!=null){
var img3 = new Image();
img3.src = cheminsculpt+srcsculpture;
img3.onload = function(){
if(volets=='furno'){
ctx.drawImage(img3, 175, 235);
}else{
ctx.drawImage(img3, 175, 242);
}
}
}
}}}}
Thank you. (Sorry for my English, I speak French)
I think this has to do with images being cached, and the onload firing before it is set.
You might need to try setting onload before you set src. See this article about the problem.