Getting 2 canvas images to appear with 1 button - javascript

I'm trying to get multiple canvas images to appear with 1 button press. I can get one image to work perfect, but the second one I can't. I know that ID's have to be unique and that only the first canvas will have an image currently.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<div class="bg">
<img src="Assets/Images/background.png" alt="background">
</div>
<section class="content">
<img id="taxi" src="Assets/Images/PV.png" width="106" height="53">
<canvas id="myCanvas" width="106" height="53"
style="border:1px solid #d3d3d3; position:absolute; left:510px;top:117px;">
Your browser does not support the HTML5 canvas tag.</canvas>
<canvas id="myCanvas" width="106" height="53"
style="border:1px solid #d3d3d3; position:absolute; left:310px;top:117px;">
Your browser does not support the HTML5 canvas tag.</canvas>
<p><button onclick="myCanvas()">Try it</button></p>
</section>
</body>
</html>
JS
function myCanvas() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("taxi");
ctx.drawImage(img,0,0,106,53);
}
I know that I can get it work by changing one the id="myCanvas" in the HTML and repeating the current lines in the script to get it to work. But the end web page will have lots of canvas' and I didn't want to keep repeating the javascript code.
Is there a simple way of doing what I am trying to achieve?

HTML elements cannot have the same id. You'll need to retrieve your elemnts some other way. There are many ways; getElementsByTagName, getElementsByClassName, querySelectorAll, ... etc.
Use querySelectorAll(".content > canvas"); This will select all direct children that are canvas elements in the element that has the class of "content" (which in this case is your section element).
function myCanvas() {
document.querySelectorAll(".content > canvas").forEach(c=>{
var ctx = c.getContext("2d");
var img = document.getElementById("taxi");
ctx.drawImage(img,0,0,106,53);
});
}
Basic example:
function myCanvas() {
document.querySelectorAll(".content > canvas").forEach(c=>{
var ctx = c.getContext("2d");
var img = document.getElementById("taxi");
ctx.drawImage(img,0,0,106,53);
});
}
<section class="content">
<img id="taxi" src="https://static-s.aa-cdn.net/img/ios/899287106/45820b5b6bba46c7fcd853a46d554a34?v=1" width="106" height="53">
<canvas width="106" height="53" style="border:1px solid #d3d3d3; position:absolute; left:510px;top:117px;">
Your browser does not support the HTML5 canvas tag.</canvas>
<canvas width="106" height="53" style="border:1px solid #d3d3d3; position:absolute; left:310px;top:117px;">
Your browser does not support the HTML5 canvas tag.</canvas>
<p><button onclick="myCanvas()">Try it</button></p>
</section>

Related

Cannot render an image when source passed in as a variable

I am writing a code that takes in an image and pastes it into an HTML canvas. The code works when I declare my <img> in the HTML file, but this does not allow the user to input a new file.
Here is the html structure (the program works if the tag line is put back in:
<style type='text/css'>
canvas{
border: 10px solid black;
}
</style>
</head>
<body>
<canvas id='balls'>
</canvas>
<canvas id='hide' style:'border: 10px solid black;'>
<!-- <img id="taco" width="300" height="300" src="prime.png"> -->
</canvas>
<div>
<input id='url' placeholder="image url">
<button id='submit'>Submit</button>
</div>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
<script src="client.js" async defer></script>
</body>
</html>
Here is the portion of JS code I am working on:
$(document).ready(onReady);
var canvas = document.querySelector('canvas');
canvas.width = 300;
canvas.height= 300;
let bounced = false;
let newPic = `id="taco" width="300" height="300" src="prime.png"`
function onReady(){
$('#submit').on('click', updateImage)
$('#hide').empty()
$('#hide').append(`<img ${newPic}>`)
makeCanvas();
setup();
animate();
}
function updateImage() {
newPic= `id="taco" width="300" height="300" src="${$('#url').val()}" alt="prime.png"`
//console.log(newPic)
$('#hide').empty()
$('#hide').append(`<img ${newPic}>`)
makeCanvas();
setup();
animate();
}
let c, can, ctx, img
function makeCanvas(){
c = canvas.getContext('2d');
can=document.getElementById("hide");
console.log(can)
can.width = 300;
can.height = 300;
ctx=can.getContext("2d");
img=document.getElementById("taco");
ctx.drawImage(img,10,10);
console.log(img)
console.log(ctx.drawImage(img,10,10))
}
My console.log statements for img are identical when the code in the HTML file is placed back in.
When you're setting up your canvas, your image isn't loaded at all. So your
ctx.drawImage(img,10,10);
call just draws... an unloaded image... an empty set of bytes... Nothing.
So you should first load your image. After that, drawing stuff will easily be done. Here's a little code example:
var canv, ctx, img;
function setup() {
//Setting up canvas
//Fetching Context
ctx = canv.getContext("2d");
//Now drawing our image
ctx.drawImage(img,10,10);
}
img = new Image();
img.onload = setup; //We'll setup the canvas after the image is fully loaded
img.src = "your/path/or/variable/pointing/to/your/image.ext";
Hope it helps!

Change the background of canvas element to url

So what I want to do is I want to change the HTML line of code from
<canvas id="canvas" width="1000" height="500" class="canvas"></canvas>
to have a style attribute added to look like this:
<canvas id="canvas" width="1000" height="500" class="canvas" style="background: url(SOMEURL);"></canvas>
The JavaScript I have tried is this:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
Then inside a function That I call after 4 seconds I have:
canvas.style.backgroundImage =
'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAAH0CAYAAACuKActAAAI4ElEQVR4nO3c0WnDMBSG0X+mrJId+pxBPIgH8SRZRH1RwA2GUNxyb9NzQGDHljF5+xByAgAAAAAAAAAAAAAAf8tIriMZB+P2zecsv/WOAAAA8K+M5F4xFwAAANh5juyRrLsV9XX325fjkWzznq3ivQEAAOCt7AN9JLdHiM/zdSTXebzNsR7NBQAAAE54CvTlYF/6Mq9d5vnlaC4AAABwwsEK+uGH30Zynx+Xux/NBQAAAE54sQd9zGjfdivpy2PfuT3oAAAAcMJIPt5hVP+PAAAAcEp1WAt0AAAAiEAHAACAFqrDWqADAABABDoAAAC0UB3WAh0AAAAi0AEAAKCF6rAW6AAAABCBDgAAAC1Uh7VABwAAgAh0AAAAaKE6rAU6AAAARKADAABAC9VhLdABAAAgAh0AAABaqA5rgQ4AAAAR6AAAANBCdVgLdAAAAIhABwAAgBaqw1qgAwAAQAQ6AAAAtFAd1gIdAAAAItABAACgheqwFugAAAAQgQ4AAAAtVIe1QAcAAIAIdAAAAGihOqwFOgAAAESgAwAAQAvVYS3QAQAAIAIdAAAAWqgOa4EOAAAAEegAAADQQnVYC3QAAACIQAcAAIAWqsNaoAMAAEAEOgAAALRQHdYCHQAAACLQAQAAoIXqsBboAAAAEIEOAAAALVSHtUA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB+wicgsAnCtx8FrwAAAABJRU5ErkJggg==);';
But after the line of code gets run it now looks like:
<canvas id="canvas" width="1000" height="500" class="canvas" style=""></canvas>
The style is just blank. What I am I doing wrong? Thanks. Will pick the best answer. Thanks!
You can use jQuery for that and set the background property to desired url of your canvas element. In your case, a base64 image. Example:
setTimeout(function() {
$('#canvas').css('background',"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAAH0CAYAAACuKActAAAI4ElEQVR4nO3c0WnDMBSG0X+mrJId+pxBPIgH8SRZRH1RwA2GUNxyb9NzQGDHljF5+xByAgAAAAAAAAAAAAAAf8tIriMZB+P2zecsv/WOAAAA8K+M5F4xFwAAANh5juyRrLsV9XX325fjkWzznq3ivQEAAOCt7AN9JLdHiM/zdSTXebzNsR7NBQAAAE54CvTlYF/6Mq9d5vnlaC4AAABwwsEK+uGH30Zynx+Xux/NBQAAAE54sQd9zGjfdivpy2PfuT3oAAAAcMJIPt5hVP+PAAAAcEp1WAt0AAAAiEAHAACAFqrDWqADAABABDoAAAC0UB3WAh0AAAAi0AEAAKCF6rAW6AAAABCBDgAAAC1Uh7VABwAAgAh0AAAAaKE6rAU6AAAARKADAABAC9VhLdABAAAgAh0AAABaqA5rgQ4AAAAR6AAAANBCdVgLdAAAAIhABwAAgBaqw1qgAwAAQAQ6AAAAtFAd1gIdAAAAItABAACgheqwFugAAAAQgQ4AAAAtVIe1QAc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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB+wicgsAnCtx8FrwAAAABJRU5ErkJggg==)");
}, 4000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="1000" height="500" class="canvas" style="background: url('https://i.imgur.com/FUsyxR5.jpg');"></canvas>

Draw a pendulum using DOM

Here is the code, I am drawing 2 circles and 2 lines and an additional line appears parallel to second line.Here is a screenshot
<html>
<head>
<body>
<canvas id="Panel" height=500 width=500 style ="border: 1px dotted green">
</canvas>
</body>
<script>
var canvas = document.getElementById("Panel");
var draw = canvas.getContext("2d");
draw.beginPath();
draw.arc(canvas.width/2,100,10,2*Math.PI,false);
draw.fillSytle="black";
draw.fill();
draw.arc(canvas.width/2,200,10,2*Math.PI,false);
draw.fillSytle="black";
draw.fill();
draw.moveTo(canvas.width/2,0);
draw.lineTo(canvas.width/2,100);
draw.moveTo(canvas.width/2,100);
draw.lineTo(canvas.width/2,200);
draw.stroke();
</script>
</head>
</html>
Check the snippet below. You just need to draw two separate forms
var canvas = document.getElementById("Panel");
var draw = canvas.getContext("2d");
draw.beginPath();
draw.arc(canvas.width/2 -50,200,10,2*Math.PI,false);
draw.fillSytle="black";
draw.fill();
draw.moveTo(canvas.width/2 -50,0);
draw.lineTo(canvas.width/2 -50,200);
draw.stroke();
var draww = canvas.getContext("2d");
draww.beginPath();
draww.arc(canvas.width/2 +50,200,10,2*Math.PI,false);
draww.fillSytle="black";
draww.fill();
draww.moveTo(canvas.width/2 +50,0);
draww.lineTo(canvas.width/2 +50,200);
draww.stroke();
<canvas id="Panel" height=500 width=500 style ="border: 1px dotted green">
</canvas>

Copy dynamic canvas into another canvas not working

I`m dealing with a video communication based on canvas.
Today, I meet a weird bug when I try to capture the video into another canvas. It sometimes worked, but sometimes not.
Here`s the code.
$('#snap-button').on('click', function () {
var source = $('#video')[0];
var target = $('#photo')[0];
var context = target.getContext('2d');
context.drawImage(source, 0, 0, 800, 600);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- video -->
<canvas id="video" width="800" height="600"></canvas>
<!-- snapshot -->
<canvas id="photo" width="800" height="600"></canvas>
<button id="snap-button"></button>
```
But when I test this bug, I replace the video canvas with static canvas, such as draw a retangle, it worked 100% correctly, but dynamic is almost not worked.
What should I do ? Thanks!
Edit this code below how you want. This is working example how you can make snapshot from video into canvas.
var v = document.getElementById("video1");
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
$("#snap-button").click(function(){
ctx.drawImage(v,5,5,260,125)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Video to use:</p>
<video id="video1" controls width="270" autoplay>
<source src="http://www.w3schools.com/tags/mov_bbb.mp4" type='video/mp4'>
<source src="http://www.w3schools.com/tags/mov_bbb.ogg" type='video/ogg'>
<source src=http://www.w3schools.com/tags/"mov_bbb.webm" type='video/webm'>
</video>
<p>Snapshot:</p>
<canvas id="myCanvas" width="270" height="135" style="border:1px solid #d3d3d3;"></canvas>
<br><br>
<input type="button" id="snap-button" value="Snap shot">
Source: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_canvas_drawimage_video

How to change canvas image on click?

I am trying to change the image of canvas on click according to count of click being even or odd.
Basically i want to make a zero and cross game in which image on canvas changes to a cross or zero depending upon the count of mouse click.How to track count of click on canvas? Please help.
Please guide me as i am a beginner in html.
<!DOCTYPE html>
<head>
<title> samp1 </title>
</head>
<body>
<canvas id="mycanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
<style>
#mycanvas {
margin-top:10px;
margin-left:10px;
}
</style>
<img src="http://images.all-free- download.com/images/graphicthumb/roses_554954.jpg" id="my" width="200" height="100"/>
<img src="http://images.all-free-download.com/images/graphicthumb/flower_lighting_554944.jpg" id="ny" width="200" height="100"/>
<script>
var i=0;
function fn(){
if(i%2==0)
ctx.drawImage(im,0,0,can.width,can.height);
else
ctx.drawImage(in,0,0,can.width,can.height);
i++;}
var can = document.getElementById("mycanvas");
var ctx = can.getContext("2d");
var im=document.getElementById("my");
var in=document.getElementById("ny");
can.addEventListener("click", fn, false);
</script>
</body>
</html>
I see 2 very small errors:
'in' is a reserved word in javascript.
you have a space in the URL for the 'my' img element
With those corrected your codes should work the way you want.
Here is a fiddle to demonstrate:
http://jsfiddle.net/w09tyftt/1/
<style>
#mycanvas {
margin-top:10px;
margin-left:10px;
}
</style>
<canvas id="mycanvas" width="200" height="100" style="border:1px solid #000000;">
<img src="http://images.all-free-download.com/images/graphicthumb/roses_554954.jpg" id="my" width="200" height="100" />
<img src="http://images.all-free-download.com/images/graphicthumb/flower_lighting_554944.jpg" id="ny" width="200" height="100" />
<script>
var i = 0;
function fn() {
if (i % 2 == 0) ctx.drawImage(im, 0, 0, can.width, can.height);
else ctx.drawImage(vin, 0, 0, can.width, can.height);
i++;
}
var can = document.getElementById("mycanvas");
var ctx = can.getContext("2d");
var im = document.getElementById("my");
var vin = document.getElementById("ny");
can.addEventListener("click", fn, false);
</script>

Categories

Resources