var canvas = document.getElementById("canvasPnl");
var context = canvas.getContext('2d');
var locationtxt = "Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude;
var imageObj = new Image();
imageObj.src = document.getElementById("tempImg").src;
imageObj.onload = function () {
var x = 188;
var y = 30;
var width = 200;
var height = 137;
context.drawImage(imageObj, x, y, width, height);
context.font = "20pt Calibri";
context.fillText(locationtxt, 40, 40);
};
<canvas id="canvasPnl" width="132" height="120" style="border:0px solid #d3d3d3;"></canvas>
The size of the image is becoming bigger and it is not fitting in canvas and also the image is rotated.
How to get original image in canvas?
Ok, take a look at your reworked code below.
Notice "imageObj.src = document.getElementById("tempImg").src;" must go after imageObj.onload.
I have no access to your locationtxt or your tempImg, so I assume you are sure they are not the source of your problem.
This line of code will take an image of ANY size and force it to fit in your specified canvas size by scaling it. When it scales, you may get image distortion if your canvas size is not proportional to your image size.
context.drawImage(imageObj,0,0,imageObj.width,imageObj.height,0,0,canvas.width,canvas.height);
Here is your code -- just modified a bit :)
var canvas = document.getElementById("canvasPnl");
var context = canvas.getContext('2d');
var locationtxt = "Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude;
var imageObj = new Image();
imageObj.onload = function () {
context.drawImage(imageObj,0,0,imageObj.width,imageObj.height,0,0,canvas.width,canvas.height);
context.font = "20pt Calibri";
context.fillText(locationtxt, 40, 40);
};
imageObj.src = document.getElementById("tempImg").src;
<html>
<head>
<title></title>
</head>
<style type="text/css">
#mycanvas
{
border: 1px solid black;
}
</style>
<script type="text/javascript">
window.addEventListener('load', function () {
var img = new Image, ctx = document.getElementById('myCanvas').getContext('2d');
var img1=new Image;
img.src = 'ship.png';
img1.src='3D025.jpg';
img.addEventListener('load', function () {
var width = img.naturalWidth; // this will be 300
var height = img.naturalHeight; // this will be 400
var interval = setInterval(function() {
var x = 260, y = 0;
return function () {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img1, 0, y);
ctx.drawImage(img, x, 300,width,height);
x += 1;
if (x > ctx.canvas.width) {
x = 260;
width=width-10;
height=height-10;
ctx.drawImage(img, x, 300,width,height);
}
if (x == 750) {
x = 260;
}
};
}(), 1000/40);
}, false);
}, false);
</script>
<body>
<canvas id="myCanvas" height="600" width="1000"></canvas>
</body>
</html>
Related
Currently, I am making a game and in need of making the image rotate toward the cursor. I am using node but the image is in a js tag in the HTML file that uses ctx to draw the image.
If I put a ctx.rotate(angle); pretty much anywhere it will rotate everything; player, map, etc. I need help so that only the player is rotated
this is a simplified version of my code:
<canvas id="ctx" width="200" height="200"></canvas>
<script>
//game
var ctx = document.getElementById("ctx").getContext("2d");
var WIDTH = 200;
var HEIGHT = 200;
var Img = {};
//player
Img.player = new Image();
Img.player.src = '/client/img/player.png';
var Player = function(/*node*/){
ctx.drawImage(Img.player, ...);
}
//map
Img.map = new Image();
Img.map.src = '/client/img/map.png';
//display everything
setInterval(function(){
ctx.clearRect(0,0,200,200);
drawMap();
for(var i in Player.list)
Player.list[i].draw();
},1000/60);
//functions
//move map so that player is always in the middle
var drawMap= function(){
var x = WIDTH/2 - Player.list[/*node*/].x;
var y = HEIGHT/2 - Player.list[/*node*/].y;
ctx.drawImage(Img.map,x,y);
}
</script>
Here's an example of what you may be looking for
const ctx = document.getElementById("ctx").getContext("2d");
const WIDTH = 500,
HEIGHT = 500;
document.getElementById("ctx").height = HEIGHT;
document.getElementById("ctx").width = WIDTH;
var Player = {
x: 50,
y: 55,
angle: 0
}
document.addEventListener("mousemove", (event) => {
var x = event.clientX - Player.x,
y = event.clientY- Player.y,
angle = Math.atan2(y,x);
Player.angle = angle
})
function draw() {
window.requestAnimationFrame(draw);
ctx.clearRect(0, 0, WIDTH, HEIGHT);
ctx.save();
ctx.translate(Player.x, Player.y);
ctx.rotate(Player.angle);
ctx.translate(-Player.x, -Player.y);
ctx.fillRect(Player.x, Player.y, 20, 20);
ctx.restore();
ctx.fillRect(150, 50, 20, 20);
}
draw();
<canvas id="ctx"></canvas>
jsfiddle here
Hope this helps!
I'm trying to create a canvas where I have an image as a background that repeats horizontally and adapts the height automatically.
I've managed to repeat the background image following the x-axis but I'm unable to make the height responsive.
This is my code so far:
const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");
const bg = new Image();
bg.src = "http://lorempixel.com/100/100";
const draw = () => {
const ptrn = ctx.createPattern(bg, "repeat-x");
ctx.fillStyle = ptrn;
ctx.fillRect(0, 0, canvas.width, canvas.height);
requestAnimationFrame(draw);
};
draw();
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<canvas id="canvas" width="1000" height="200"></canvas>
<script src="index.js"></script>
</body>
</html>
TLDR: I would like to be able to have an image within my canvas that repeats horizontally and its height is responsive.
Thanks in advance.
Hopefully the explanation in the comments answers your question. Feel free to ask for clarification.
const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");
// First stretch the canvas so we can get
// the full size of teh browser window
cvs.style.height = '100vh';
cvs.style.width = '100vw';
// Now adjust actual canvas size to match
const {width, height} = cvs.getBoundingClientRect();
cvs.height = height;
cvs.width = width;
const bg = new Image();
// Should always wait for onload
// before drawing to prevent race condition.
bg.onload = ()=>{
var x=0;
while(x < cvs.width){
ctx.drawImage(bg, x, 0, 100, cvs.height);
x += bg.width;
}
// draw the image a bunch of times
// var x=0, y=0;
// while(x < cvs.width && y < cvs.height){
// ctx.drawImage(bg, x, y);
// x += bg.width;
// if(x > cvs.width){
// x = 0;
// y += bg.height;
// }
// }
};
bg.src = "http://lorempixel.com/100/100";
<canvas id="canvas"></canvas>
<script src="index.js"></script>
If I got it right you want to fill the height and repeat horizontally, is that correct?
const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");
var bg = new Image();
bg.src = "http://lorempixel.com/100/100";
var tempCanvas = document.createElement("canvas"),
tCtx = tempCanvas.getContext("2d");
var imgWidth = 200;
var imgHeight = 200;
const draw = () => {
tempCanvas.width = imgWidth;
tempCanvas.height = imgHeight;
tCtx.drawImage(bg, 0, 0, 100, 100, 0, 0, imgWidth, imgHeight);
const ptrn = ctx.createPattern(tempCanvas , "repeat-x");
ctx.fillStyle = ptrn;
ctx.fillRect(0, 0, canvas.width, canvas.height);
requestAnimationFrame(draw);
};
bg.onload = () => {
draw();
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<canvas id="canvas" width="1000" height="200"></canvas>
<script src="index.js"></script>
</body>
</html>
try setting up the image size to match the canvas size just like that:
bg.src = "http://lorempixel.com/200/200";
Cheers! :)
I am new here, so please be consider.
I've created a new canvas and created a rects in the canvas , when I set a background to the canvas I have a terrible problem that The background is on the shapes
Here is the code:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var BB = canvas.getBoundingClientRect();
var offsetX = BB.left;
var offsetY = BB.top;
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var background = new Image();
background.src = "url_to_image";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
<canvas id="canvas" width=450 height=700></canvas>
Thanks
Edit:
I found in my code a function of fillStyle that change my background,
so I delete it and instead of this I put this:
var w = canvas.width;
var h = canvas.height
var img = new Image();
img.src = "http://www.girija.info/wp-content/uploads/2015/08/Paznja-Sabranost-450x700.png";
img.onload = function () {
var pattern = ctx.createPattern(img, "repeat");
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, w, h);
};
//ctx.fillStyle = "#FAF7F8";
rect(0, 0, WIDTH, HEIGHT);
// redraw each rect in the rects[] array
for (var i = 0; i < rects.length; i++) {
var r = rects[i];
ctx.fillStyle = 'red';
rect(r.x, r.y, r.width, r.height);
}
But every drag of the rect (the rects loaded from stack and can be draggable) the background color of the rect change
You can set the background using the css property
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var BB = canvas.getBoundingClientRect();
var offsetX = BB.left;
var offsetY = BB.top;
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
ctx.rect(10, 10, 100, 100);
ctx.fill();
canvas.style.backgroundImage = 'url(https://picsum.photos/450/700)';
<canvas id="canvas" width=450 height=700></canvas>
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
background_image();
function background_image()
{
background_image = new Image();
background_image.src = 'https://image.ibb.co/kmV8kz/photodune_2359510_smiles_l_22.png';
background_image.onload = function(){
context.drawImage(background_image, 0, 0);
}
}
<canvas id="canvas" width=450 height=700></canvas>
I wrote the following code in my text editor:
<!DOCTYPE HTML><html>
<head>
<script>
window.onload = function()
{
var canvas = document.getElementById("canvasArea");
var context = canvas.getContext("2d");
var ball = new Image();
var smallImage = "https://i.warosu.org/data/sci/img/0076/83/1448614341262.png";
var ballXPos = 75;
var ballYPos = 15;
var ballWidth = 90;
var ballHeight = 90;
var reflectAdj = 3.5;
var reflectAlpha = .4;
var reflect Y = (2*ballYPos) + (2*(ballHeight-reflectAdj));
var gradLV = context.createLinearGradient(0, 0, 0, canvas.height);
ball.onload = function()
{
gradLV.addColorStop( 0, "lightskyblue");
gradLV.addColorStop(.3, "orange");
gradLV.addColorStop(1, "blue");
context.fillStyle = gradLV;
context.fillRect(0, 0, canvs.width, canvas.height);
context.translate(0, reflectY);
context.scale(1,-1);
context.globalAlpha = reflectAlpha;
context.drawImage(ball, ballXpos, ballYpos, ballWidth, ballHeight);
}
}
</script>
</head>
<body>
<div style = "width:400px; height:210px; margin:0 auto; padding:5px;">
<canvas id = "canvasArea" width = "400" height = "210"
style = "border:2px solid black">
Your browser doesn't currently support HTML5 Canvas.
</canvas>
</div>
</body>
</html>
In this code, the canvas is supposed to show a mirrored object, but the canvas is completely blank. Can someone please tell me what I did wrong/ PLease and thank you.
Your code was full of a number of small errors, most of which were typos. You were also failing to specify the image URL as the src of the new Image() constructor.
The code below fixes these issues and provides visual output on the canvas. I'm not sure exactly what mirror effect you're going for, but hopefully this sets you on the right path.
window.onload = function() {
var canvas = document.getElementById("canvasArea");
var context = canvas.getContext("2d");
var ball = new Image();
ball.src = "https://i.warosu.org/data/sci/img/0076/83/1448614341262.png";
var ballXPos = 75;
var ballYPos = 15;
var ballWidth = 90;
var ballHeight = 90;
var reflectAdj = 3.5;
var reflectAlpha = .4;
var reflectY = (2*ballYPos) + (2*(ballHeight-reflectAdj));
var gradLV = context.createLinearGradient(0, 0, 0, canvas.height);
ball.onload = function() {
gradLV.addColorStop( 0, "lightskyblue");
gradLV.addColorStop(.3, "orange");
gradLV.addColorStop(1, "blue");
context.fillStyle = gradLV;
context.fillRect(0, 0, canvas.width, canvas.height);
context.translate(0, reflectY);
context.scale(1,-1);
context.globalAlpha = reflectAlpha;
context.drawImage(ball, ballXPos, ballYPos, ballWidth, ballHeight);
}
}
<div style = "width:400px; height:210px; margin:0 auto; padding:5px;">
<canvas id = "canvasArea" width = "400" height = "210" style = "border:2px solid black">
Your browser doesn't currently support HTML5 Canvas.
</canvas>
</div>
I have 2 images on canvas and i want to make imageObg to animate. Actually i want it to make a linear move to the right.I found a way to animate an object like a rectangle but i cant animate an image object that i use from another source.
Is there anyway that can i manage to do i? Does anyone knows?
window.onload = function() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
var imageObj2 = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 69, 130);
};
imageObj2.onload = function() {
context.drawImage(imageObj2, 0, 0);
};
imageObj.src = 'http://imageshack.com/a/img745/822/pXDK5F.png'
imageObj2.src = 'http://i.dailymail.co.uk/i/pix/2014/09/04/1409790551890_wps_28_Astronaut_Reid_Wiseman_po.jpg'
};
body {
background-color: black
}
<div id='d1' style="position:absolute; top:80px; left:150px; z-index:1">
<canvas id='myCanvas' width='962' height='500' style="border:10px solid #ffffff;">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
Just two things.
Set a periodically render routine using setInterval.
Set a move (or physics) routine, call it after each render.
window.onload = function() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
var imageObj2 = new Image();
imageObj.src = 'http://imageshack.com/a/img745/822/pXDK5F.png'
imageObj2.src = 'http://i.dailymail.co.uk/i/pix/2014/09/04/1409790551890_wps_28_Astronaut_Reid_Wiseman_po.jpg'
window.setInterval(renderFrame, 50);
var ship = {
x: 69,
y: 130
};
function renderFrame() {
moveShip();
context.clearRect(0, 0, canvas.width, canvas.height);
if (imageObj.complete) {
context.drawImage(imageObj2, 0, 0);
}
if (imageObj.complete) {
context.drawImage(imageObj, ship.x, ship.y);
}
}
function moveShip() {
ship.x += 20;
if (ship.x > canvas.width) {
ship.x = 0 - imageObj.width;
ship.y = Math.random() * 250 + 50;
}
}
};
body {
background-color: black
}
<div id='d1' style="position:absolute; top:80px; left:150px; z-index:1">
<canvas id='myCanvas' width='962' height='500' style="border:10px solid #ffffff;">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
Just increase the x position of the image with a setInterval command.
var img = document.createElement("IMG");
var img.src = [Image Source];
var x = 0;
window.setInterval(function() {
x ++;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(img, x, 0);
}, 50);
Hope this helps.
Edit:
Here is a JSFiddle Example.