When you put a picture named logo.png in the same directory as this html file and try to run it in a web browser the picture only appears 1 times out of 10 refreshes in IE and doesn't appear the first time in Firefox but does appear after further refreshes.
What the heck is going on ?
(drawImage() method is called in the showIntro() function)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Example 1 - Title Screen</title>
<script>
window.onload = function () {
var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var State = {
_current: 0,
INTRO: 0,
LOADING: 1,
LOADED: 2
}
window.addEventListener('click', handleClick, false);
window.addEventListener('resize', doResize, false);
doResize();
function handleClick() {
State._current = State.LOADING;
fadeToWhite();
}
function doResize() {
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
switch (State._current) {
case State.INTRO:
showIntro();
break;
}
}
function fadeToWhite(alphaVal) {
// If the function hasn't received any parameters, start with 0.02
var alphaVal = (alphaVal == undefined) ? 0.02 : parseFloat(alphaVal) + 0.02;
// Set the color to white
c.fillStyle = '#FFFFFF';
// Set the Global Alpha
c.globalAlpha = alphaVal;
// Make a rectangle as big as the canvas
c.fillRect(0, 0, canvas.width, canvas.height);
if (alphaVal < 1.0) {
setTimeout(function () {
fadeToWhite(alphaVal);
}, 30);
}
}
function showIntro() {
var phrase = "Click or tap the screen to start the game";
// Clear the canvas
c.clearRect(0, 0, canvas.width, canvas.height);
// Make a nice blue gradient
var grd = c.createLinearGradient(0, canvas.height, canvas.width, 0);
grd.addColorStop(0, '#ceefff');
grd.addColorStop(1, '#52bcff');
c.fillStyle = grd;
c.fillRect(0, 0, canvas.width, canvas.height);
var logoImg = new Image();
logoImg.src = './logo.png';
// Store the original width value so that we can keep
// the same width/height ratio later
var originalWidth = logoImg.width;
// Compute the new width and height values
logoImg.width = Math.round((50 * document.body.clientWidth) / 100);
logoImg.height = Math.round((logoImg.width * logoImg.height) / originalWidth);
// Create an small utility object
var logo = {
img: logoImg,
x: (canvas.width / 2) - (logoImg.width / 2),
y: (canvas.height / 2) - (logoImg.height / 2)
}
// Present the image
c.drawImage(logo.img, logo.x, logo.y, logo.img.width, logo.img.height);
// Change the color to black
c.fillStyle = '#000000';
c.font = 'bold 16px Arial, sans-serif';
var textSize = c.measureText(phrase);
var xCoord = (canvas.width / 2) - (textSize.width / 2);
c.fillText(phrase, xCoord, (logo.y + logo.img.height) + 50);
}
}
</script>
<style type="text/css" media="screen">
html { height: 100%; overflow: hidden }
body {
margin: 0px;
padding: 0px;
height: 100%;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="100" height="100">
Your browser doesn't include support for the canvas tag.
</canvas>
</body>
</html>
The problem is that you aren't waiting for the image to load when you call drawImage().
You could use something like:
logo.img.onload = function(){
c.drawImage(logo.img, logo.x, logo.y, logo.img.width, logo.img.height);
};
Although make sure you don't start modifying the canvas until this has happened.
Related
I'm trying to have an image on my website become saturated at the same location the mouse is. When the mouse moves the saturation effect goes with it, and the area previously hovered over becomes grayscale again. I'm thinking this effect could be accomplished using saturate(), however I haven't had any success with it. Additionally, I would like the effect to be circular without hard edges similar to this.
Example of what it would look like (orange arrow indicating where the mouse is).
Any help or insight would be appreciated, thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content= "width=device-width, initial-scale=1.0" />
</head>
<script>
const size = 250;
var radius = 30;
var rad = Math.PI / 180;
var canvas = document.querySelector("canvas")
var ctx = canvas.getContext("2d");
canvas.width = size;
canvas.height = size;
var image = new Image();
image.onload = demo
image.src = "https://picsum.photos/250"
function draw_circle(x, y, radius) {
ctx.clearRect(0, 0, size, size);
ctx.drawImage(image, 0, 0); // image to change
ctx.globalCompositeOperation = "saturation";
ctx.beginPath();
ctx.fillStyle = "hsl(0,100%,50%)"; // saturation at 100%
ctx.arc(x, y, radius, 0, 360 * rad, false);
ctx.fill()
ctx.closePath();
ctx.globalCompositeOperation = "source-over"; // restore default comp
}
function demo() {
ctx.drawImage(image, 0, 0); // image to change
canvas.addEventListener('mousemove', function(ev) {
var cx = ev.offsetX
var cy = ev.offsetY
draw_circle(cx, cy, radius)
})
}
</script>
<canvas></canvas>
</html>
Using a canvas we can try. Here's a start inspired by How can I adjust the huse, saturation, and lightness of in image in HTML5 Canvas?.
const size = 250;
var radius = 30;
var rad = Math.PI / 180;
var canvas = document.querySelector("canvas")
var ctx = canvas.getContext("2d");
canvas.width = size;
canvas.height = size;
var image = new Image();
image.onload = demo
image.src = "https://picsum.photos/250"
function draw_circle(x, y, radius) {
ctx.clearRect(0, 0, size, size);
ctx.drawImage(image, 0, 0); // image to change
ctx.globalCompositeOperation = "saturation";
ctx.beginPath();
ctx.fillStyle = "hsl(0,100%,50%)"; // saturation at 100%
ctx.arc(x, y, radius, 0, 360 * rad, false);
ctx.fill()
ctx.closePath();
ctx.globalCompositeOperation = "source-over"; // restore default comp
}
function demo() {
ctx.drawImage(image, 0, 0); // image to change
canvas.addEventListener('mousemove', function(ev) {
var cx = ev.offsetX
var cy = ev.offsetY
draw_circle(cx, cy, radius)
})
}
<canvas></canvas>
This is a simple answer (change the logic of the program as you want):
<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
width: 200px;
height: 150px;
}
.image {
width: 100%;
height: 100%;
}
</style>
<script>
const width = 50;
const height = 50;
function create() {
const element = document.createElement("div");
element.id = "filtered";
element.style.width = `${width}px`;
element.style.height = `${height}px`;
element.style.borderRadius = "50%";
element.style.position = "absolute";
element.style.backgroundColor = "red";
element.style.opacity = "0.2";
element.style.zIndex = "2";
return element;
}
function changePos(e) {
x = e.clientX;
y = e.clientY;
let element = document.getElementById("filtered");
if (!element) {
element = create();
document.getElementById("focusArea").appendChild(element);
}
element.style.left = `${x - width / 2}px`;
element.style.top = `${y - height / 2}px`;
}
function removeElement() {
if (document.getElementById("filtered")) {
document.getElementById("filtered").remove();
}
}
</script>
</head>
<body>
<div
id="focusArea"
onmouseleave="removeElement()"
onmousemove="changePos(event)"
class="relative"
>
<img
src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/800px-Image_created_with_a_mobile_phone.png"
class="image"
/>
</div>
</body>
</html>
I am trying to make the images race each other and once one of the images passes the finish line display the winner.
I have some old code I used for the animation but i don't know how to implement the images with it.
<html>
<head>
<title>Canvas Race</title>
<script src="jquery-2.2.3.js"></script>
<style type="text/css">
canvas {
border: 1px solid black;
background-image: url("http://www.gamefromscratch.com/image.axd?picture=road2048v2.png");
background-size: 200px 300px;
background-position-y: -81px;
}
</style>
</head>
<body>
<canvas id="canvas" width="1100" height="150" >
<script>
var blueCar = new Image();
var redCar = new Image();
// images
function image(){
blueCar.src = "http://worldartsme.com/images/car-top-view clipart-1.jpg";
redCar.src = "http://images.clipartpanda.com/car-clipart-top-view-free-vector-red-racing-car-top-view_099252_Red_racing_car_top_view.png";
}
window.onload = function draw(){
var ctx = document.getElementById('canvas').getContext('2d');
ctx.globalCompositeOperation = 'destination-over';
window.requestAnimationFrame(draw);
window.requestAnimationFrame(animate);
// finish line
ctx.beginPath();
ctx.moveTo(1020, 150);
ctx.lineTo(1020, 0);
ctx.strokeStyle = "#FFEF0E";
ctx.stroke();
//blue car
ctx.save();
if(blueCar.complete){
ctx.drawImage(blueCar, 10, 10, 100, 60);
}
// red car
if(redCar.complete){
ctx.drawImage(redCar, 10, 80, 100, 60);
}
}
image();
</script>
</canvas>
<div id="winner"></div>
</body>
</html>
Old code:
I want to use this old code but i don't know what to remove and how to add the images that i have above for the cars. As you can see for this code i created squares instead of images.
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
// drawing red square
function drawRedRect(redCar, ctx) {
ctx.beginPath();
ctx.drawImage(redCar, 5, 5);
}
// finish line
function drawFinishLine(ctx){
ctx.beginPath();
ctx.moveTo(1040, 150);
ctx.lineTo(1040, 0);
ctx.stroke();
}
// this is drawing the blue square
function drawBlueRect(blueRectangle, ctx){
ctx.beginPath();
ctx.rect(blueRectangle.x, blueRectangle.y, blueRectangle.width, blueRectangle.height);
ctx.fillStyle = 'blue';
ctx.fill();
}
// red square animation
function animate(lastTime, redCar, blueRectangle, runAnimation, canvas, ctx) {
if(runAnimation.value) {
// update
var time = (new Date()).getTime();
var timeDiff = time - lastTime;
// pixels / second
var redSpeed = Math.floor((Math.random() * 400) + 1);
var blueSpeed = Math.floor((Math.random() * 400) + 1);
var linearDistEachFrameRed = redSpeed * timeDiff / 1000;
var linearDistEachFrameBlue = blueSpeed * timeDiff / 1000;
var currentX = redRectangle.x;
var currentZ = blueRectangle.x;
if(currentX < canvas.width - redRectangle.width - redRectangle.borderWidth / 2) {
var newX = currentX + linearDistEachFrameRed;
redRectangle.x = newX;
}
if(currentZ < canvas.width - blueRectangle.width - blueRectangle.borderWidth / 2) {
var newZ = currentZ + linearDistEachFrameBlue;
blueRectangle.x = newZ;
}
console.log(redSpeed);
console.log(blueSpeed);
// clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw
drawFinishLine(ctx);
drawRedRect(redRectangle, ctx);
drawBlueRect(blueRectangle, ctx);
//winner(win);
// request new frame
requestAnimFrame(function() {
animate(time, redRectangle, blueRectangle, runAnimation, canvas, ctx);
});
}
}
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var win = document.getElementById('Winner')
//blue square
var blueRectangle = {
x: 5, y: 30, width: 45, height: 25, borderWidth:5
};
//red square
var redRectangle = {
x: 5,
y: 90,
width: 45,
height: 25,
borderWidth: 5
};
/!*
* define the runAnimation boolean as an obect
* so that it can be modified by reference
*!/
var runAnimation = {
value: false
};
// add click listener to canvas
document.getElementById('myCanvas').addEventListener('click', function() {
// flip flag
runAnimation.value = !runAnimation.value;
if(runAnimation.value) {
var date = new Date();
var time = date.getTime();
animate(time, redRectangle, blueRectangle, runAnimation, canvas, ctx);
}
});
drawFinishLine(ctx);
drawRedRect(redRectangle, ctx);
drawBlueRect(blueRectangle, ctx);
//winner(win);
Here is some of your code refactored to race car images:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// game vars
var redRectangle={x:5,y:40,width:62,height:21};
var goldRectangle={x:5,y:75,width:62,height:21};
var finishX=450;
// animation vars
var nextTime=0;
var delay=1000/60;
// image vars and call start() when all images are loaded
var red=new Image();
red.onload=start;
red.src='https://dl.dropboxusercontent.com/u/139992952/multple/car1.png';
var gold=new Image();
gold.onload=start;
gold.src='https://dl.dropboxusercontent.com/u/139992952/multple/car2.png';
var imageCount=2;
function start(){
// return if all the images aren't loaded
if(--imageCount>0){return;}
// start the animation loop
requestAnimationFrame(animate);
}
function animate(time){
// has the desired time elapsed?
if(time<nextTime){requestAnimationFrame(animate);return;}
nextTime=time+delay;
// update the car positions
redRectangle.x+=Math.random()*5;
goldRectangle.x+=Math.random()*5;
// draw the current scene
ctx.clearRect(0,0,canvas.width,canvas.height);
drawFinishLine(ctx);
drawRedRect(redRectangle, ctx);
drawgoldRect(goldRectangle, ctx);
// request another animation loop
hasRedWon=redRectangle.x+redRectangle.width>finishX;
hasGoldWon=goldRectangle.x+goldRectangle.width>finishX;
// alert if race is over
if(hasRedWon){ alert('Red wins'); return; }
if(hasGoldWon){ alert('Gold wins'); return; }
// race is still going, request another animation loop
requestAnimationFrame(animate);
}
// draw images instead of rects
function drawRedRect(redRectangle, ctx){
ctx.drawImage(red, redRectangle.x, redRectangle.y, redRectangle.width, redRectangle.height);
}
// draw images instead of rects
function drawgoldRect(goldRectangle, ctx){
ctx.drawImage(gold, goldRectangle.x, goldRectangle.y, goldRectangle.width, goldRectangle.height);
}
// draw finish line
function drawFinishLine(){
ctx.fillRect(finishX,0,5,ch);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=500 height=300></canvas>
I have a canvas that I have in html that is supposed to be 25% of the page. I made a variable named width in javascript, and put it's value as 25%. When I make a context.clearRect(); with the width variable as the width parameter, it doesn't fix it what I was trying to do (which I have done tons of times) which is when the player rectangle moves, the clearRect keeps the background circulating so the rectangle isn't drawing (leaving a mark). Here is my width variable:
var width = 25%;
Here is my clearRect();
context.clearRect(0, 0, width, height);
Edit: I guess I will also post my whole entire code, to be easier.
<html>
<head>
<title></title>
<style type="text/css">
body {
background-color: #222222;
}
canvas {
background-color: #000000;
width: 25%;
height: 400px;
}
</style>
</head>
<body>
<canvas id="mainCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys = [];
var speed = 4;
var width = 25%;
var height = 400;
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e) {
delete keys[e.keyCode];
}, false);
var player = {
x: 10,
y: 10,
width: 30,
height: 30
};
function game() {
update();
render();
}
function update() {
if (keys[40]) player.y++ * speed;
if (keys[38]) player.y-- * speed;
if (keys[37]) player.x-- * speed;
if (keys[39]) player.x++ * speed;
}
function render() {
context.clearRect(0, 0, (canvas.width * 0.25)), height);
context.fillStyle = "white";
context.fillRect(player.x, player.y, player.width, player.height);
}
setInterval(function() {
game();
}, 1000/30);
</script>
You need to use something like this:
context.clearRect(0, 0, (canvas.width * 0.25), height);
Try this?
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
body {
background-color: #222222;
}
canvas {
background-color: #000000;
width: 25%;
height: 400px;
}
</style>
</head>
<body>
<canvas id="mainCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys = [];
var speed = 4;
// var width = 25%;
var height = 400;
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e) {
delete keys[e.keyCode];
}, false);
var player = {
x: 10,
y: 10,
width: 30,
height: 30
};
function game() {
update();
render();
}
function update() {
if (keys[40]) player.y++ * speed;
if (keys[38]) player.y-- * speed;
if (keys[37]) player.x-- * speed;
if (keys[39]) player.x++ * speed;
}
function render() {
context.clearRect(0, 0, (canvas.width * 0.25), height);
context.fillStyle = "white";
context.fillRect(player.x, player.y, player.width, player.height);
}
setInterval(function() {
game();
}, 1000/30);
</script>
</body>
</html>
Not sure what you actually wanted to ask yet your code has two syntax errors - thus it does not execute correctly:
var keys = [];
var speed = 4;
//var width = 25%; //This is no valid assignment and the value is not used..
var height = 400;
and
function render() {
//context.clearRect(0, 0, (canvas.width * 0.25)), height); //One bracket too much, can skip both tho..
context.clearRect(0, 0, canvas.width * 0.25, height);
You need to put your canvas in a container, and set up the container the way you want, then you make your canvas 100% of the containers properties using
clientHeight
and
clientWidth
JSFiddle: https://jsfiddle.net/53n2s0s9/
i want to move html canvas horizontally, then rotate it, and then again move it horizontally. problem is, that after i rotate it and want to move it again, rotation dissapear. what i am doing wrong ? thanks, my code is below
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<style type="text/css">
#canvas {
width:400px;
height:400px;
border:1px solid red;
}
</style>
<canvas id="canvas"></canvas>
<script type="text/javascript">
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
var counterx = 0;
var canvasWidth = 400;
var canvasHeight = 400;
var imageObj = new Image();
imageObj.onload = function() {
ctx.drawImage(imageObj, counterx,0 ,69, 50);
};
imageObj.src = 'test.png';
function moveRight() {
ctx.save();
counterx += 5;
ctx.clearRect(0 ,0 ,canvasWidth, canvasHeight);
ctx.drawImage(imageObj, counterx,0 ,69, 50);
ctx.restore();
}
function rotate() {
ctx.save();
ctx.translate(counterx, 0);
ctx.rotate(Math.PI / 4);
ctx.clearRect(0 ,0 ,canvasWidth, canvasHeight);
ctx.drawImage(imageObj, counterx,0 ,69, 50);
ctx.restore();
}
</script>
<a onclick="moveRight(); return false;" href="#">move right</a>
<a onclick="rotate(); return false;" href="#">rotate</a>
</body>
</html>
I would recommend accumulating the values, then do an absolute transform only when needed. A little refactoring can also make it easier to track these changes, here that would be to use a common update method.
For example:
var rotation = 0;
var counterx = 0;
function moveRight() {
counterx += 5;
update();
}
function rotate() {
rotation += Math.PI / 4
update();
}
function update() {
ctx.clearRect(0 ,0 ,canvasWidth, canvasHeight);
ctx.translate(counterx, 0); // absolute translate
ctx.rotate(rotation); // absolute rotation
ctx.drawImage(imageObj, 0, 0, 69, 50); // we are already at counterx
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset all transformations
}
And if you want to rotate by image's center, just replace the drawImage line above with:
ctx.drawImage(imageObj, -69/2, -50/2, 69, 50);
Live demo
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var canvasWidth = 400;
var canvasHeight = 400;
var imageObj = new Image();
var rotation = 0;
var counterx = 0;
c.width = canvasWidth;
c.height = canvasHeight;
imageObj.onload = update;
imageObj.src = 'http://i.imgur.com/mP58PXJ.png';
function moveRight() {
counterx += 5;
update();
}
function rotate() {
rotation += Math.PI / 4
update();
}
function update() {
var iw = imageObj.width, ih = imageObj.height;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.translate(counterx, ih); // absolute translate
ctx.rotate(rotation); // absolute rotation
ctx.drawImage(imageObj, -iw*0.5, -ih*0.5); // we are already at counterx
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset all transformations
}
#canvas {
width: 400px;
height: 400px;
border: 1px solid red;
}
<canvas id="canvas"></canvas>
<a onclick="moveRight(); return false;" href="#">move right</a>
<a onclick="rotate(); return false;" href="#">rotate</a>
I am new to html5 development could anyone tell me how to make text to move one side to other horizontally inside canvas..
Here's an example of how to animate text back and forth across the screen:
<html>
<head>
<title>HTML 5 Animated Text</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var context;
var text = "";
var textDirection ="";
$(function()
{
context = document.getElementById("cvs").getContext("2d");
setInterval("animate()", 30);
textDirection ="right";
textXpos = 5;
text = "Animation!";
});
function animate() {
// Clear screen
context.clearRect(0, 0, 500, 500);
context.globalAlpha = 1;
context.fillStyle = '#fff';
context.fillRect(0, 0, 500, 500);
var metrics = context.measureText(text);
var textWidth = metrics.width;
if (textDirection == "right") {
textXpos += 10;
if (textXpos > 500 - textWidth) {
textDirection = "left";
}
}
else {
textXpos -= 10;
if (textXpos < 10) {
textDirection = "right";
}
}
context.font = '20px _sans';
context.fillStyle = '#FF0000';
context.textBaseline = 'top';
context.fillText ( text, textXpos, 180);
}
</script>
</head>
<body>
<div id="page">
<canvas id="cvs" width="500" height="500">
Your browser does not support the HTML 5 Canvas.
</canvas>
</div>
</body>
</html>
In action: http://jsfiddle.net/bS79G/
You can also use the canvas store(), translate() and restore() methods to animate the text.
suppose if you want to move the text from right side to left side, then you can use the following code snippet:
Refer site: http://www.authorcode.com/text-animation-in-html5/
var can, ctx, step, steps = 0,
delay = 20;
function init() {
can = document.getElementById("MyCanvas1");
ctx = can.getContext("2d");
ctx.fillStyle = "blue";
ctx.font = "20pt Verdana";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
step = 0;
steps = can.height + 50;
RunTextRightToLeft();
}
function RunTextRightToLeft() {
step++;
ctx.clearRect(0, 0, can.width, can.height);
ctx.save();
ctx.translate(can.width / 2, step);
ctx.fillText("Welcome", 0, 0);
ctx.restore();
if (step == steps)
step = 0;
if (step < steps)
var t = setTimeout('RunTextRightToLeft()', delay);
}