I am currently having issues with displaying images in the HTML canvas. I am still new and I am quite tired so its likely theres somthing stupid I did not do. Heres the code:
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.height = 695;
canvas.width = 1515;
//Images
const BG = new Image();
BG.src = "C:\Users\MSI\Documents\ABGG Remastered\StartImg.png"
ctx.drawImage(BG, 0, 0);
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas"></canvas>
<script src="C:\Users\MSI\Documents\ABGG Remastered\mainScript.js">
</script>
<style>
canvas {
border: 1px solid;
}
</style>
</body>
</html>
Thanks for the help!
Loading an image is not instantly so you need to wait for it to be loaded first which you can do with the onload function of the image
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.height = 695;
canvas.width = 1515;
//Images
const BG = new Image();
BG.src = "https://images3.alphacoders.com/899/thumb-1920-899727.jpg"
BG.onload = () => {ctx.drawImage(BG, 0, 0);}
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas"></canvas>
<script src="C:\Users\MSI\Documents\ABGG Remastered\mainScript.js">
</script>
<style>
canvas {
border: 1px solid;
}
</style>
</body>
</html>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.height = 695;
canvas.width = 1515;
//Images
const BG = new Image();
BG.addEventListener('load', function() {
ctx.drawImage(BG, 20,20);
})
BG.src = "C:\\Users\\dhrum\\Documents\\Projects\\WizemenDesktop\\WizemenDesktop\\Assets\\icon.png"
</script>
I changed to code to this and it works. First of all, I'd recommend using a method to wait for the image to load, and then draw it (slow servers or large files can take a little to load, and hence wont be drawn if not loaded).
Second of all, your issue that that \ escapes the character, and you'd want to do \\, where the first \ will escape the 2nd \ which would make the actual value of the string with only 1 \.
To understand what escaping a character means, you can go here
Related
I have a .js file with a simple animation that I'd like to use as a website's background. I'm able to put it onto the page and all that- but the text appears below the animation instead of over it. I've tried looking up solutions but all I've been able to find is instructions for making setting a .png/.jpg as the background. I'm very new to programming, so I haven't the slightest idea how I'd do this. Thanks for any help.
EDIT: Here's the code I'm trying to use!
<!DOCTYPE html>
<html>
<head>
<title>Scrolling Page</title>
</head>
<body style="background-color: black;">
<canvas id="canvas1"></canvas>
<h1>Text</h1>
<p>text</p>
</body>
</html>
<script src="mainscript.js"></script>
mainscript.js is:
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
can.width = 9200;
can.height = 630;
var img = new Image();
img.src = "tempimage.png";
window.onload = function() {
var imgWidth = 0;
var scrollSpeed = 10;
function loop()
{
ctx.drawImage(img, imgWidth, 0);
ctx.drawImage(img, imgWidth - can.width, 0);
imgWidth -= scrollSpeed;
if (-imgWidth == can.width)
imgWidth = 0;
window.requestAnimationFrame(loop);
}
loop();
Because we're not talking about using just a picture as a background and instead an HTML canvas element that is being animated, you'll need to use CSS to layer the canvas element that you want to use as a background behind the rest of the page content. To do that, you can position the background element with position:absolute and then place it behind everything else with z-index:-1.
<!DOCTYPE html>
<html>
<head>
<title>Scrolling Page</title>
<style>
#canvas1 {
position:absolute; /* Take the element out of the normal document flow */
z-index:-1; /* Place the element behind normal content */
top:0; /* Start at top of viewport */
left:0; /* Start at left edge of viewport */
}
</style>
</head>
<body>
<canvas id="canvas1"></canvas>
<h1>Text</h1>
<p>text</p>
<script>
var can = document.getElementById("canvas1");
var ctx = can.getContext('2d');
can.width = 9200;
can.height = 630;
var img = new Image();
img.src = "https://cdn.pixabay.com/photo/2019/02/19/19/45/thumbs-up-4007573__340.png";
window.onload = function() {
var imgWidth = 0;
var scrollSpeed = 10;
function loop() {
ctx.drawImage(img, imgWidth, 0);
ctx.drawImage(img, imgWidth - can.width, 0);
imgWidth -= scrollSpeed;
if (-imgWidth == can.width) {
imgWidth = 0;
}
window.requestAnimationFrame(loop);
}
loop();
}
</script>
</body>
</html>
I am trying to build a basic game and somehow got really hung up on the first few steps. I am trying to create a canvas, the the color of the canvas, and then append to a div element. Every time I load this I either get an error, or nothing. Even if the 2 console.logs load properly. Please help!
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dodge</title>
<script src="//code.jquery.com/jquery.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/journal/bootstrap.min.css" rel="stylesheet" integrity="sha256-fHWoqb8bPKjLiC7AuV6qy/lt0hrzfwM0ciyAu7Haf5w= sha512-3t2GeiCRNeKhZnUaUMygGiLKZzb/vPhvfw3y1Rt2FCwKuRaLVrOCTpavIYsZ4xqM52mbO7M93NaXbm/9dOA2Og==" crossorigin="anonymous">
<script src="../../../game.js">
</script>
</head>
<body>
<center>
<h1 id="h1">Dodge the enemy by pressing the left and right arrow keys!</h1>
<button
id="play"
class="btn btn-primary">Play game!</button>
</br>
</br>
<button
id="again"
class="btn btn-primary">Play Again!</button>
<div id="play-area">
</div>
</center>
</body>
</html>`
And heres the JS:
$(function () {
function createCanvas(width, height, id) {
var canvas = document.createElement("canvas");
var id2 = "#" + id;
canvas.width = width;
canvas.height = height;
canvas.id = id;
$(id2).css("color", "lawngreen");
$("#game-area").append(canvas);
}
$("#play").click(function () {
console.log("hello");
createCanvas(900, 900, "game-canvas");
console.log("hi!");
});
});
First you create the canvas object correctly, but you should also append it to the body. This is done after basic parameters are set.
After that you can manipulate the css with jQuery.
It works in my fiddle.
Check it out here: https://jsfiddle.net/xu15q5h8/
I changed your code to point out how it correctly works:
$(function () {
function createCanvas(width, height, id) {
var canvas = document.createElement('canvas');
var body = document.getElementsByTagName("body")[0];
canvas.id = id;
canvas.width = width;
canvas.height = height;
body.appendChild(canvas);
$('canvas').css('background-color', 'rgba(158, 167, 184, 0.2)');
cursorLayer = document.getElementById("CursorLayer");
console.log(cursorLayer);
}
$("#play").click(function () {
console.log("hello");
createCanvas(900, 900, "game-canvas");
alert("hi!");
});
});
Why not just draw the color onto the canvas instead of using CSS.
function createCanvas(width, height, id) {
var canvas = document.createElement("canvas");
var id2 = "#" + id;
canvas.width = width;
canvas.height = height;
canvas.id = id;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "lawngreen";
ctx.fillRect (0, 0, width, height);
$("#play-area").append(canvas);
}
Here is the modified code demo.
I want to be able to click on a button on my page and load an image into a canvas at some X,Y coordinates?
The following code is what I have below. I would like the image to be in either image/photo.jpg or in the same directory but preferably in a subdirectory of the main page.
**Question: How to make a JPG show up in a canvas with the click of a button on the web page?
Code:
<!DOCTYPE html>
<html>
<script>
function draw(){
var ctx = document.getElementById("myCanvas").getContext("2d");
var img = new Image():
// img.src = "2c.jpg";
img.src = "/images/2c.jpg";
ctx.drawImage(img,0,0);
}
</script>
<body background="Black">
<div align="center">
<button type="button" onclick="draw()">Show Image on Canvas</button>
<canvas id="myCanvas" width="900" height="400" style="border:2px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="20px Arial";
ctx.fillText("Royal Flush $",500,50);
ctx.fillText("Striaght Flush $",500,80);
ctx.fillText("Flush $",500,110);
ctx.fillText("Four of a Kind $",500,140);
ctx.fillText("Full House $",500,170);
ctx.fillText("Three of a Kind $",500,200);
ctx.fillText("Two Pair $",500,230);
ctx.fillText("Pair of ACES $",500,260);
ctx.rect(495,10,270,350);
ctx.stroke();
</script>
</body>
</html>
March 6th, 2014 Code:
How is the following code not working. Do you have to have an ID tag on Canvas. The page will display but for some reason the image will not when the button is clicked. The image is in the same directory that my index.html file is in.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
canvas{
border: 5px solid black;
}
</style>
</html>
<button id="galaxy">Add image #1</button>
<button id="circles">Add image #2</button><span></span>
<canvas width="500" height="500"></canvas>
<script>
var Images = {};
function loadImages(list){
var total = 0;
document.querySelector("span").innerText = "...Loading...";
for(var i = 0; i < list.length; i++){
var img = new Image();
Images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
document.querySelector("span").innerText = "...Loaded.";
}
};
img.src = list[i].url;
}
}
function drawImage(img){
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(Images[img], 0, 0, 50, 50);
}
loadImages([{
name: "2c.jpg",
url: "mp.jpg"
},{
name: "mp.jpg",
url: "mp.jpg"
}]);
document.querySelector("#galaxy").addEventListener("click", function(){
drawImage("galaxy");
});
document.querySelector("#circles").addEventListener("click", function(){
drawImage("weirdCircles");
});
</script>
</html>
Wait till the image is loaded before drawing:
var img = new Image();
img.onload = function(){ /*or*/ img.addEventListener("load", function(){
ctx.drawImage(img,0,0); ctx.drawImage(img,0,0);
}; };
img.src = "/images/2c.jpg";
Demo: http://jsfiddle.net/DerekL/YcLgw/
If you have more than one image in your game,
It is better to preload all images before it starts.
Preload images: http://jsfiddle.net/DerekL/uCQAH/ (Without jQuery: http://jsfiddle.net/DerekL/Lr9Gb/)
If you are more familiar with OOP: http://jsfiddle.net/DerekL/2F2gu/
function ImageCollection(list, callback){
var total = 0, images = {}; //private :)
for(var i = 0; i < list.length; i++){
var img = new Image();
images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
callback && callback();
}
};
img.src = list[i].url;
}
this.get = function(name){
return images[name] || (function(){throw "Not exist"})();
};
}
//Create an ImageCollection to load and store my images
var images = new ImageCollection([{
name: "MyImage", url: "//example.com/example.jpg"
}]);
//To pick and draw an image from the collection:
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(images.get("MyImage"), 0, 0);
This question about crossfading images already gave an answer to the crossfading solution in Canvas. I am trying to do the same thing, only difference is that i am trying to fade images that are loaded on runtime.
The images are loaded propperly but no fade is visible. Is this not working because of the loaded images? Thanks.
HTML
<div id="wrapper">
<canvas id="bg1"></canvas>
<canvas id="bg2"></canvas>
</div>
JS
var toggle = true;
var canvas = document.getElementById('bg1');
canvas.width = $(document).width();
canvas.height = $(document).height();
var ctx = canvas.getContext('2d');
var canvas2 = document.getElementById('bg2');
canvas2.width = $(document).width();
canvas2.height = $(document).height();
var ctx2 = canvas2.getContext('2d');
var image = new Image();
image.src = 'download1.jpg';
var image2 = new Image();
image2.src = 'download2.jpg';
image.onload = function() {
ctx.drawImage(image, 0, 0, 200, 100);
ctx2.drawImage(image2, 0, 0, 200, 100);
};
$('#wrapper').click(function () {
if (toggle)
{
$('#bg2').fadeIn();
$('#bg1').fadeOut();
}
else
{
$('#bg1').fadeIn();
$('#bg2').fadeOut();
}
toggle = !toggle;
});
Yep, you need to give your images time to load.
But also, jQuery cannot do fadeIn/fadeout on a canvas element so you will have to do that manually.
Demo: http://jsfiddle.net/m1erickson/zw9S4/
Code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
$("#fade").hide();
var imageURLs=[]; // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-2.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-4.jpg");
loadAllImages();
//
function loadAllImages(){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
$("#fade").show();
ctx.drawImage(imgs[0],0,0);
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var fadeOutIndex=imgs.length-1;
var fadeInIndex=0;
var fadePct=0;
function animateFade(){
if(fadePct>100){return;}
requestAnimationFrame(animateFade);
ctx.clearRect(0,0,canvas.width,canvas.height);
draw(imgs[fadeInIndex],fadePct/100);
draw(imgs[fadeOutIndex],(1-fadePct/100));
fadePct++;
}
function draw(img,opacity){
ctx.save();
ctx.globalAlpha=opacity;
ctx.drawImage(img,0,0);
ctx.restore();
}
$("#fade").click(function(){
fadePct=0;
if(++fadeOutIndex == imgs.length){fadeOutIndex=0;}
if(++fadeInIndex == imgs.length){fadeInIndex=0;}
animateFade();
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="fade">Fade to next Image</button><br>
<canvas id="canvas" width=204 height=204></canvas><br>
</body>
</html>
Try to fade in/out the images directly on the canvas instead of fading in and out the canvas elements (or there is not really any point using the canvas as you could use image elements instead).
First, of course, wait for the images to load:
var isBusy = false, /// for fade loop
count = 2; /// number of images to load
image = new Image();
image2 = new Image();
/// setup load handler
image.onload = image2.onload = handleLoad;
image.src = 'download1.jpg';
image2.src = 'download2.jpg';
function handleLoad() {
count--;
if (count === 0) {
/// when loaded draw a single image onto canvas
ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
}
};
Now we can change the click handler a little bit around and use canvas only to do the fade in of the next image:
$('#wrapper').click(function () {
var img, /// current image to fade in
opacity = 0; /// current globalAlpha of canvas
/// if we're in a fade exit until done
if (isBusy) return;
isBusy = true;
/// what image to use
img = toggle ? image2 : image;
/// fade in
(function fadeIn() {
/// set alpha
ctx.globalAlpha = opacity;
/// draw image with current alpha
ctx.drawImage(img, 0, 0, ctx.canvas.width, ctx.canvas.height);
/// increase alpha to 1, then exit resetting isBusy flag
opacity += 0.02;
if (opacity < 1)
requestAnimationFrame(fadeIn);
else
isBusy = false;
})();
toggle = !toggle;
});
Online demo
Hope this helps.
I would like to draw an image opened with the HTML5 File API on a canvas.
In the handleFiles(e) method, I can access the File with e.target.files[0] but I can't draw that image directly using drawImage. How do I draw an image from the File API on HTML5 canvas?
Here is the code I have used:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script>
window.onload = function() {
var input = document.getElementById('input');
input.addEventListener('change', handleFiles);
}
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.drawImage(e.target.files[0], 20,20);
alert('the image is drawn');
}
</script>
</head>
<body>
<h1>Test</h1>
<input type="file" id="input"/>
<canvas width="400" height="300" id="canvas"/>
</body>
</html>
You have a File instance which is not an image.
To get an image, use new Image(). The src needs to be an URL referencing to the selected File. You can use URL.createObjectURL to get an URL referencing to a Blob (a File is also a Blob): http://jsfiddle.net/t7mv6/86/.
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image;
img.onload = function() {
ctx.drawImage(img, 20,20);
alert('the image is drawn');
}
img.src = URL.createObjectURL(e.target.files[0]);
Note: be sure to revoke the object url when you are done with it otherwise you'll leak memory. If you're not doing anything too crazy, you can just stick a URL.revokeObjectURL(img.src) in the img.onload function.
References:
https://developer.mozilla.org/en/DOM/File
http://html5demos.com/file-api
Live Example
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
var url = URL.createObjectURL(e.target.files[0]);
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 20, 20);
}
img.src = url;
}
window.URL.createObjectUrldocs
You could also use the FileReader instead to create the object URL.
The FileReader has slightly better browser support.
The FileReader approach works in FF6 / Chrome. I'm not certain whether setting Img.src to a Blob is valid and cross-browser though.
Creating object urls is the correct way to do it.
Edit:
As mentioned in the commment window.URL support whilst offline seems unavailable in FF6/Chrome.
Here is a complete example (Fiddle) using FileReader (which has better browser support as mentioned by Raynos). In this example I also scale Canvas to fit the image.
In real life example you might scale the image to some maximum so that your form will not blow up ;-). Here is an example with scaling (Fiddle).
var URL = window.webkitURL || window.URL;
window.onload = function() {
var input = document.getElementById('input');
input.addEventListener('change', handleFiles, false);
// set original canvas dimensions as max
var canvas = document.getElementById('canvas');
canvas.dataMaxWidth = canvas.width;
canvas.dataMaxHeight = canvas.height;
}
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
var reader = new FileReader();
var file = e.target.files[0];
// load to image to get it's width/height
var img = new Image();
img.onload = function() {
// setup scaled dimensions
var scaled = getScaledDim(img, ctx.canvas.dataMaxWidth, ctx.canvas.dataMaxHeight);
// scale canvas to image
ctx.canvas.width = scaled.width;
ctx.canvas.height = scaled.height;
// draw image
ctx.drawImage(img, 0, 0
, ctx.canvas.width, ctx.canvas.height
);
}
// this is to setup loading the image
reader.onloadend = function () {
img.src = reader.result;
}
// this is to read the file
reader.readAsDataURL(file);
}
// returns scaled dimensions object
function getScaledDim(img, maxWidth, maxHeight) {
var scaled = {
ratio: img.width / img.height,
width: img.width,
height: img.height
}
if (scaled.width > maxWidth) {
scaled.width = maxWidth;
scaled.height = scaled.width / scaled.ratio;
}
if (scaled.height > maxHeight) {
scaled.height = maxHeight;
scaled.width = scaled.height / scaled.ratio;
}
return scaled;
}
canvas {
border:1px solid black
}
<input type="file" id="input"/>
<div>
<canvas width="400" height="300" id="canvas"/>
</div>