How to add two image in canvas element in html..? - javascript

So far, I create a canvas and I add two images one over another.how to create a eraser to scratch upper image and then shows it lower image ..pls help me..
It's very essential to me ..I surprise to my brother birthday...pls help me..Thank you..
I just want to know..
how to add two images on canvas? In my code is it right..?
how to create eraser for clearing upper image.. with touchmove in javaScript
javaScript
window.addEventListener("click",play);
function play() { document.getElementById("song").play();
}
window.onload = function () {
var img1= new Image();
img1.src = 'https://dl.dropbox.com/s/xxz0nbrplhst2w2/20201010_174008.jpg?';
img1.onload = function ()
{
filling1(img1);
}
var img2=new Image();
img2.src=
"https://dl.dropbox.com/s/zpoxft30lzrr5mg/20201012_102150.jpg";
img2.onload = function ()
{
filling2(img2);
}
function filling1(img) {
var canvas= document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0,1012,1012);
}
function filling2(img) {
var canvas= document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0,1078,1260);
}
}
CSS
body { background: #dddddd;
}
canvas
{
margin: 50px;
padding: 0px;
border: thin inset #aaaaaa;
width: 300px;
height: 400px;
position:absolute;
background-image:url("");
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#9"></script>
</head>
<body>
<div>
<canvas id="canvas"> Canvas not supported </canvas>
</div>
<audio controls style="display:none;"loop id="song" >
<source src="https://dl.dropbox.com/s/bsgain4rsi5q44m/Happy-Birthday-Instrumental">
<!-- <source src="https://dl.dropbox.com/s/bbxas9a8jvts3ng/birthday%20wishes%20song%20slow%20motion"> -->
<script>
Swal.fire("Just Scratch It").then((value)=> {Swal.fire('I hope you like it','Thank you','success');});
</script>
</audio>
</body>
</html>
It is another code for touchmove but it doesn't work as a eraser ..why..?
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");
canvas.width = 300;
canvas.height = 380;
var mx, my;
function Circle(x, y){
this.x = x;
this.y = y;
this.radius = 30;
this.draw = function(){
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
c.stroke();
}
this.update = function(){
canvas.addEventListener("touchmove",
function(e){
mx = e.touches[0].clientX;
my = e.touches[0].clientY;
circle.x = mx;
circle.y = my;
});
if(this.x + this.radius > canvas.width){
this.x = canvas.width / 2;
}
if(this.x - this.radius < 0){
this.x = canvas.width / 2;
}
if(this.y + this.radius > canvas.height){
this.y = canvas.height / 2;
}
if(this.y - this.radius < 0){
this.y = canvas.height / 2;
}
circle.draw()
}
}
var circle = new Circle(100, 100);
function a(){
requestAnimationFrame(a);
c.clearRect(0, 0, canvas.width, canvas.height);
circle.update();
}
a();
</script>
</body>
</html>

window.addEventListener("click",play);
function play() { document.getElementById("song").play();}
var canvas= document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 300;
canvas.height = 400;
window.onload = function () {
var img = new Image();
img.onload = () => ctx.drawImage(img,0,0,300,400);
img.src = "https://dl.dropbox.com/s/zpoxft30lzrr5mg/20201012_102150.jpg";
}
function Circle(x, y){
this.x = x;
this.y = y;
this.radius = 30;
this.draw = function(){
ctx.save();
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
ctx.restore();
}
}
var circle = new Circle(100, 100);
canvas.addEventListener("touchmove", function(e){
var mx = e.touches[0].clientX;
var my = e.touches[0].clientY;
move(mx, my);
});
canvas.addEventListener("mousemove", function(e){
var mx = e.offsetX;
var my = e.offsetY;
move(mx, my);
});
function move(x,y){
circle.x = x;
circle.y = y;
circle.draw();
}
body { background: #dddddd;}
canvas {
margin: 20px;
padding: 0px;
border: thin inset #aaaaaa;
width: 300px;
height: 400px;
position:absolute;
background-image: url("https://dl.dropbox.com/s/xxz0nbrplhst2w2/20201010_174008.jpg");
background-size: 100% 100%;;
}
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#9"></script>
</head>
<body>
<div>
<canvas id="canvas"> Canvas not supported </canvas>
</div>
<audio controls style="display:none;"loop id="song" >
<source src="https://dl.dropbox.com/s/bsgain4rsi5q44m/Happy-Birthday-Instrumental">
<!-- <source src="https://dl.dropbox.com/s/bbxas9a8jvts3ng/birthday%20wishes%20song%20slow%20motion"> -->
</audio>
<script>
Swal.fire("Just Scratch It").then((value)=> {Swal.fire('I hope you like it','Thank you','success');});
</script>
</body>
</html>

Related

Making an object move back and forth in javascript [duplicate]

So I have this rectangle that animates across to the right. How can I get the rectangle to reverse it when it hits the boundaries. I'm trying to make it go back and forth.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 50;
var width = 10;
var height = 10;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, y, width, height);
x++;
if(x <= 490) {
setTimeout(animate, 33);
}
}
animate();
}
</script>
</head>
<body>
<canvas id="canvas" width="500" height="400"
style="border: 1px solid #000000;"></canvas>
</body>
</html>
https://codepen.io/forTheLoveOfCode/pen/wqdpeg
Is that what you need? (link to codepen above).
var canvas = document.getElementById("canvas_id");
var context = canvas.getContext('2d');
var x=5;
var y=5;
var velocity = 10;
function move(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
x =x + velocity
if ((x+50)>canvas.width || x<0){
velocity *=-1;
}
draw()
}
function draw(){
context.fillStyle = "#E80C7A";
context.strokeStyle = "#000000";
context.lineWidth = '3';
context.fillRect(x, y, 50, 100);
context.strokeRect(x, y, 50, 100);
}
setInterval(move, 100);
<html>
<body>
<canvas id = "canvas_id">
</canvas>
</body>
</html>
here's a solution with boundaries detection
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 50;
var width = 10;
var height = 10;
var speed = 10; // speed
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, y, width, height);
if(
(x >= 500 - width && speed > 0) || // going to the right and bound reached
(x <= 0 && speed < 0) // going to the left and bound reached
) {
speed *= -1; // inverting the direction
}
x += speed;
setTimeout(animate, 33);
}
animate();
}
<canvas id="canvas" width="500" height="400"
style="border: 1px solid #000000;"></canvas>
consider using requestAnimationFrame instead of setTimeout to do this kind of work.

how i can draw image and rotate with shadow in html 5 canvas

i write a canvas rotate image and trying to add drop shadows.
anyone can help me to how i can add a different shadow style for images inside canvas. i need drop shadows like as this image for result :
enter image description here
context.shadowColor = "rgba( 0, 0, 0, 0.3 )";
context.shadowOffsetX = 6;
context.shadowOffsetY = 6;
context.shadowBlur = 3;
context.drawImage( brolly, 25, 250 );
full code :
window.addEventListener("load", init);
var canvas = document.getElementById('c');
canvas.width = 360;
canvas.height = 360;
var context = canvas.getContext('2d');
var counter = 0;
var logoImageh = new Image();
logoImageh.src = 'http://sirati.info/tmp/h.png';
var logoImagem = new Image();
logoImagem.src = 'http://sirati.info/tmp/m.png';
TO_RADIANS = Math.PI / 180;
function init() {
setInterval(loop, 100 / 30);
}
function loop() {
context.clearRect(0, 0, canvas.width, canvas.height);
drawRotatedImage(logoImageh, 180, 180, counter++);
drawRotatedImage(logoImagem, 180, 180, counter++);
counter += 1;
}
function drawRotatedImage(image, x, y, angle) {
context.save();
context.translate(x, y);
context.rotate(angle * TO_RADIANS);
context.drawImage(image, -(image.width / 2), -(image.height / 2));
context.restore();
}
body {
margin: 0px;
padding: 0px;
text-align: center;
}
canvas {
outline: 0;
border: 1px solid #000;
margin-left: auto;
margin-right: auto;
}
<html>
<head>
<title>Simple</title>
</head>
<body>
<canvas id='c'></canvas>
</body>
</html>
i write
Add shadows to your images using in-memory canvases.
Then drawImage those in-memory canvases instead of the images. Yes, drawImage can draw other canvases as well as images!
[Addition: example code using question's code as a basis]
var canvas = document.getElementById('c');
canvas.width = 360;
canvas.height = 360;
var context = canvas.getContext('2d');
var counter = 0;
TO_RADIANS = Math.PI / 180;
var nextTime=0;
var delay=1000/60*2;
var logoImageh = new Image();
logoImageh.onload=start;
logoImageh.src = 'http://sirati.info/tmp/h.png';
var logoImagem = new Image();
logoImagem.onload=start;
logoImagem.src = 'http://sirati.info/tmp/m.png';
var imageCount=2;
//
function start(){
canvasLogoImageh=addShadowToImage(logoImageh);
canvasLogoImagem=addShadowToImage(logoImagem);
requestAnimationFrame(loop);
}
function addShadowToImage(img){
var c=document.createElement('canvas');
var cctx=c.getContext('2d');
c.width=img.width;
c.height=img.height;
cctx.shadowColor='black';
cctx.shadowBlur=10;
cctx.drawImage(img,0,0);
return(c);
}
function loop(time) {
if(time<nextTime){requestAnimationFrame(loop);return;}
nextTime=time+delay;
context.clearRect(0, 0, canvas.width, canvas.height);
drawRotatedImage(canvasLogoImageh, 180, 180, counter++);
drawRotatedImage(canvasLogoImagem, 180, 180, counter++);
counter += 0.25;
requestAnimationFrame(loop);
}
function drawRotatedImage(image, x, y, angle) {
context.save();
context.translate(x, y);
context.rotate(angle * TO_RADIANS);
context.drawImage(image, -(image.width / 2), -(image.height / 2));
context.restore();
}
body{ background-color: ivory; }
canvas{border:1px solid red; margin:0 auto; }
<canvas id="c" width=300 height=300></canvas>

Image not appearing in canvas - sometimes

This works great on all of my tests, but on the live system, I have a problem.
There are three separate but identical canvases. They are all initially painted with 640x480 jpg images. The third is then updated every second with a new 640x480 jpg image.
For some reason, the original static image for the third canvas - and that canvas only - doesn't load from the live server, only on the tests.
Here's the html:
<div style="padding: 1vw;">
<a href="/virtualscribe" class="camLink">
<div class="camDiv">
<div class="camBox" id="picBoxLeft">
<canvas id="canvasLeft" class="camBorder"></canvas>
</div>
</div>
</a>
<a href="/videos" class="camLink">
<div class="camDiv">
<div class="camBox" id="picBoxCenter">
<canvas id="canvasCenter" class="camBorder"></canvas>
</div>
</div>
</a>
<div class="camDiv">
<div class="camBox" id="picBoxRight">
<canvas id="canvasRight" class="camBorder"></canvas>
</div>
</div>
</div>
Here's the CSS:
<style>
.camBox {
max-width: 28vw;
width: 28vw;
height: 21vw;
max-height: 21vw;
display: inline-block;
}
.camDiv {
padding: 1.5vw;
display: inline-block;
}
.camBorder {
border: 0.6vw solid #fe890f;
border-top-left-radius: 3.3vw;
border-bottom-right-radius: 3.3vw;
}
.camLink {
color: transparent;
}
</style>
And here's the JavaScript:
var refreshTimer;
var imgLiveCam;
function drawPictureBox(img, canvas, text) {
var context = canvas.getContext("2d");
context.drawImage(img, 0, 0, canvas.width, canvas.height);
context.globalAlpha = 0.6;
context.fillStyle = "rgb(244,121,32)";
context.fillRect(0, canvas.height * 0.67, canvas.width, canvas.height * 0.33);
context.globalAlpha = 1;
var maxWidth = canvas.width;
var x = canvas.width / 2;
var y = canvas.height * 0.85;
context.font = canvas.width / 12 + 'px Oswald';
context.strokeStyle = 'black';
context.lineWidth = 2;
context.textAlign = "center";
context.strokeText(text, x, y, maxWidth);
context.fillStyle = 'white';
context.fillText(text, x, y, maxWidth);
};
function drawCamBox(img, logo, canvas) {
var context = canvas.getContext("2d");
context.drawImage(img, 0, 0, canvas.width, canvas.height);
context.globalAlpha = 0.6;
context.fillStyle = "rgb(244,121,32)";
context.fillRect(0, canvas.height * 0.67, canvas.width, canvas.height * 0.33);
var eSize = canvas.height / 10;
context.globalAlpha = 1;
context.drawImage(logo, 2, canvas.height * 0.67 - eSize, eSize, eSize);
var now = new Date();
var text = now.toLocaleDateString() + " " + now.toLocaleTimeString();
var maxWidth = canvas.width * 0.33;
var x = canvas.width - 10 - maxWidth;
var y = canvas.height * 0.67 - 10;
context.font = maxWidth / 10 + "px Arial";
context.strokeStyle = 'black';
context.lineWidth = 2;
context.strokeText(text, x, y, maxWidth);
context.fillStyle = 'white';
context.fillText(text, x, y, maxWidth);
text = 'View Our Production Floor';
context.textAlign = "center";
maxWidth = canvas.width;
x = canvas.width / 2;
y = canvas.height * 0.85;
context.font = canvas.width / 12 + 'px Oswald';
context.strokeText(text, x, y, maxWidth);
context.fillText(text, x, y, maxWidth);
}
function addResizeListener(fn) {
if (window.attachEvent) {
window.attachEvent('onresize', fn)
} else if (window.addEventListener) {
window.addEventListener('resize', fn, true);
};
}
function initCam() {
var imgLeft = new Image();
imgLeft.onload = function () {
var canvas = document.getElementById("canvasLeft");
var picBox = document.getElementById("picBoxLeft");
var drawFn = function () {
canvas.height = picBox.clientHeight;
canvas.width = picBox.clientWidth;
drawPictureBox(imgLeft, canvas, 'Looking for a Scribe?');
};
drawFn();
addResizeListener(drawFn);
}
var imgCenter = new Image();
imgCenter.onload = function () {
var canvas = document.getElementById("canvasCenter");
var picBox = document.getElementById("picBoxCenter");
var drawFn = function () {
canvas.height = picBox.clientHeight;
canvas.width = picBox.clientWidth;
drawPictureBox(imgCenter, canvas, 'Watch In-Depth Videos');
};
drawFn();
addResizeListener(drawFn);
}
imgLiveCam = new Image();
var logo = new Image();
logo.src = "e.png";
imgLiveCam.onload = function () {
var canvas = document.getElementById("canvasRight");
var picBox = document.getElementById("picBoxRight");
var drawFn = function () {
canvas.height = picBox.clientHeight;
canvas.width = picBox.clientWidth;
drawCamBox(imgLiveCam, logo, canvas);
};
drawFn();
imgLiveCam.onload = drawFn;
addResizeListener(drawFn);
}
imgLeft.src = "scribe.jpg";
imgCenter.src = "doc-with-spine.jpg";
imgLiveCam.src = "camloading.jpg";
refreshTimer = setTimeout(refresh, 499);
}
function refresh() {
clearTimeout(refreshTimer);
imgLiveCam.src = "http://cams.edataservices.com/17fcam.jpg?t=" + new Date().getTime();
refreshTimer = setTimeout(refresh, 1009);
}
Any idea why the third canvas starts out blank most of the time?
By adding a longer delay before starting the refresh cycle, the browsers had more time to load the initial, "default" image. I set it at 1500ms, and now it is pretty reliable.
(Thanks for the help...)

Onclick function for my shape

I need to add click to my star to turn it green. The variable is called "colorchoice" and I can't figure it out. Its a modified pong game i had to do for a project, i just can't figure out the onclick for the shape, and it needs to be vairable for wherever the star moves to.
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Mayo's Pong Game</title>
</head>
<body bgcolor="grey">
<section>
<div>
<canvas id="canvas" width="500" height="500">
This text is displayed if your browser
does not support HTML5 Canvas.
</canvas>
</div>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
// var context = canvas.getContext('2d');
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
message = 'LEVEL '+level+' Score= '+score+' Lives= '+lives;
//writeMessage(canvas, message);
paddley=mousePos.y -(rpheight/2);
if (paddley+60 > 500) {
paddley = 440;
}
paddley2=mousePos.y -(lpheight/2);
if (paddley2+60 > 500) {
paddley2 = 440;
}
}, false);
// var canvas;
var ctx;
var x = 250;
var y = 50;
var WIDTH = 520;
var HEIGHT = 520;
var message;
var level=1;
var score = 0;
var lives = 20;
var colorchoice;
function drawStar(cx, cy, spikes, outerRadius, innerRadius) {
var rot = Math.PI / 2 * 3;
var x = cx;
var y = cy;
var step = Math.PI / spikes;
ctx.strokeSyle = "#000";
ctx.beginPath();
ctx.moveTo(cx, cy - outerRadius)
for (i = 0; i < spikes; i++) {
x = cx + Math.cos(rot) * outerRadius;
y = cy + Math.sin(rot) * outerRadius;
ctx.lineTo(x, y)
rot += step
x = cx + Math.cos(rot) * innerRadius;
y = cy + Math.sin(rot) * innerRadius;
ctx.lineTo(x, y)
rot += step
}
ctx.lineTo(cx, cy - outerRadius)
ctx.closePath();
ctx.lineWidth=3;
ctx.strokeStyle=colorchoice;
ctx.stroke();
ctx.fillStyle=colorchoice;
ctx.fill();
}
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 15);
}
function draw() {
clear();
ctx.fillStyle = 'grey';
rect(0,0,WIDTH,HEIGHT);
ctx.fillStyle = 'black';
drawStar(x, y,5,20,10);
writeMessage(canvas,message);
}
function writeMessage(canvas, message) {
var context = canvas.getContext('2d');
//context.clearRect(0, 0, canvas.width, canvas.height);
context.font = '18pt Calibri';
context.fillStyle = 'black';
context.fillText(message, 20, 20);
}
init();
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX,
y: evt.clientY
};
}
</script>
</section>
<p>AUSTIN MAYO'S PONG GAME<p>
Pick a color for your paddles and balls, then click start.<br>
Warning: If you click the start button more than once, difficulty will increase!!!<p>
<button type="button" onclick="alert('PAUSED')">PAUSE</button>
<button type="button" onclick="location.reload();">RESTART</button>
<button type="button" onclick="init(canvas);">START</button>
<br>
<p>GAME MUSIC<BR>
<audio controls>
<source src="SOUNDTRACK.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>
</html>

Draw a circle in the middle of canvas

Having -
HTML -
<canvas id="myCanvas" >
</canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 30;
context.beginPath();
context.arc(centerX,centerY, radius, 0, 2 * Math.PI);
context.fillStyle = 'blue';
context.fill();
</script>
CSS-
#myCanvas {
border:2px solid;
display:inline-block;
width:500px;
height:400px;
}
http://jsfiddle.net/urielz/3E656/
but I get not accurate circle . How can I make it accurate circle ?
Demo Fiddle
If you just want set the canvas size in CSS, change your code to:
<canvas id="myCanvas"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var style = window.getComputedStyle(canvas);
if (canvas.getContext) {
canvas.width = parseInt(style.getPropertyValue('width'));
canvas.height = parseInt(style.getPropertyValue('height'));
}
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 30;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'blue';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
this.arc(x, y, radius, 0, Math.PI * 2, false);
this.fill();
</script>
You need to set explicitly the size of your canvas, otherwise it will get the default size: 300x150.
you should do something like this
<canvas id="myCanvas" width="500" height="400"></canvas>
or via javascript (before getting the context)
canvas.width = 500;
canvas.height = 400;
var context = canvas.getContext('2d');
You need to set the width of your canvas, like so:
<canvas id="myCanvas" width="500" height="400"></canvas>
Place below code after begin path:
var centerX = canvas.width;
var centerY = canvas.height;
context.arc(centerX*0.5,centerY*0.5,10,0 ,radius, 0, 2 * Math.PI);
Css:
#myCanvas {
border:2px solid;
display:inline-block;
width:600px;
height:300px;
}

Categories

Resources