I want to know how to load an image into the HTML5 canvas. Specifically, I want a script that swaps one image for another on the canvas during mouse over with the original image fading out. I am new to HTML5 and have this code:
<canvas id="myCanvas" width="500" height="500" />
<script type="text/javascript">
function drawbackground() {
char.fillStyle="blue";
cxt.fillRect(0,0,500,500);
}
var charx=0;
var chary=0;
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var char=c.getContext("2d");
drawbackground();
char.fillStyle="black";
var imgObj = new Image();
imgObj.src='map1.png';
imgObj.onload = function () {
// Draw the image on the canvas
char.drawImage(imgObj, 10, 10);
}
</script>
Is this in the right direction?
You can do this without the HTML5 Canvas. To swap an image on mouse over it is easiest to use a JavaScript Framework called jQuery, get it for free here: http://jquery.com/.
With jQuery all you need to do is something like the following:
First, create an image Tag.
<img src="image1.png" id="myimage" />
Next add JavaScript to handle the mouse over event. You can learn more about jQuery events here: http://api.jquery.com/category/events/
$("#myimage").mouseover(function() {
$(this).src = this.src.replace("image2.png");
});
The example above will change the image on mouse over. To do the fade effects, you need to do a little more: You can learn more about jQuery effects here: http://api.jquery.com/category/effects/
I would create two images for the effect and position each over the other with the css property set to hide image 2.
<div id="imageHolder">
<img src="image1.png" id="myimage1" />
<img src="image2.png" id="myimage2" style="display:none" />
</div>
Next comes the JavaScript:
$("#imageHolder").mouseover(function() {
$("#image1").fadeOut();
$("#image2").show();
});
$("#imageHolder").mouseout(function() {
$("#image1").fadeIn();
$("#image2").hide();
});
There are many ways to accomplish this and the code above is not tested, but should provide you with a basis to quickly create the desired effect.
Related
On my page I'm using the img tag to embed SVG images. Now I wanted to apply some css onto them. This works well as long as you copypaste the SVG source code directly into your page. However, if I embed them using the img src attribute, it doesn't.
Is there a way to make that work?
<style type="text/css">
path:hover {
fill:white;
}
</style>
<img src="my.svg" />
Thanks in advance!
Well it can be achieved through JQuery ( Work Around ) , this Jquery function will convert <img> tag that hold current svg image into a <svg> inline tags, you can view it in your browser debugger.In short it will mimic as if directly inserted the SVG image.
<script type="text/javascript">
$(document).ready(function() {
$('#img').each(function(){
var img = $(this);
var image_uri = img.attr('src');
$.get(image_uri, function(data) {
var svg = $(data).find('svg');
svg.removeAttr('xmlns:a');
img.replaceWith(svg);
}, 'xml');
});
});
</script>
<img id='img' src="my.svg" />
I do not think this is possible. You are correct in that using inline-SVG will allow you to manipulate the parts of the svg, but including it in an img tag will not. See http://css-tricks.com/using-svg/
I am trying to understand how to use the crossorigin attribute for the img tag. I couldn't find a good example (The ones I found about CORS enabled images are explained with JavaScript codes, therefore I couldn't see the crossorigin attribute with the img tag.
I have got a guess, please correct my mistakes if I understood something wrong.
First of all one can write the code piece below to draw an image to canvas:
<canvas id="canvas" width=400 height=400></canvas>
<br><br>
<img id="image" src="http://...." alt="" width="400" height="400">
<script>
function draw() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var img = new Image();
img.crossOrigin = "Anonymous";
img.src = document.getElementById("image").value;
context.drawImage(img, 40, 40);
}
</script>
Is the code below equivalent to the upper one? It doesn't include "img.crossOrigin" but have crossorigin attribute in the img tag.
<canvas id="canvas" width=400 height=400></canvas>
<br><br>
<img id="image" crossorigin="anonymous"src="http://...." alt="" width="400" height="400">
<script>
function draw() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var img = new Image();
img.src = document.getElementById("image").value;
context.drawImage(img, 40, 40);
}
</script>
To tell the truth I cannot make experiments because I don't know what site allows to use its images as CORS.
What I guess is that, if a site allow to use its images in canvas if the CORS request is done by anonymously you can draw it in canvas, if not you cannot draw it in canvas even if the request is done by anonymously (I am not sure if I am right here). Therefore both of the examples above must be requesting CORS anonymously.
Could you please say if both of them works the same? If not, could you please explain why and give me an example using the crossorigin attribute with the img tag?
Since you are using the #image element as the source for your image, the 2 versions of your code are roughly equivalent.
But...
The version without crossorigin="anonymous" in the img element will probably still generate a cross-domain violation.
That's because the image is originally loaded into the img element without the cross-origin flag set to anonymous.
The javascript code will likely use the cached version of the image from the img element rather than trying to reload it from http://...
This means the cached image data will still taint the canvas as containing cross-origin content.
BTW, a syntax error in your code:
// Not: img.src = document.getElementById("image").value;
img.src = document.getElementById("image").src;
I'm also curious to know if this is a best practice.
I load a sprite map:
canvas = $('#GameCanvas')[0];
context = canvas.getContext('2d');
// load sprite map
spriteMap = new Image();
spriteMap.src = "resources/spritemap.png";
Now I've loaded my sprites, I want to draw them on the screen. I can do so by using context.drawImage(..) but:
I don't know if this is the best way, instead of just extracting each image I want and storing them separately eg. var playerCharacter = [cut the image out of the sprite map]
I want to colorise the images. If I pull out a 'white' sprite, I may then want to colorise it red, green, etc. I don't know how to do this yet, but it will probably require creating a new colorised Image so I'd have to pull it out of the spritemap anyway. I don't want to be recolorising constantly.
Any idea the best way of doing this?
Performance using sprites
Phrogz has some useful FPS tests for CSS vs Canvas here: Efficiency of <canvas> and <div>s They are live tests so you can run them in the environments you want to test.
Recoloring sprites
If you want to quickly take your white sprite and create red, green and blue sprites from it, you can use globalCompositeOperation=”source-in” to do that with very little work. Just use an image editor to create a cutout of the part of the image you want to recolor. Then use the code below to automatically create different colored sprites. I did the mask below in Photoshop using the magic want tool – 2 minutes tops!
Original Fish + Mask = Green Fish
Of course, you can create any color you want...even patterns instead of solid colors!
Here’s code. You will probably have to create your own image and mask because of CORS – stupid CORS !!
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
canvas{border:1px solid red;}
#wrapper{ position:relative;}
#overlay,#base{ position:absolute; top:0; left:0;}
</style>
<script>
$(function(){
var canvas=document.getElementById("overlay");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=function(){
ctx.drawImage(img,0,0,img.width,img.height,0,0,overlay.width,overlay.height);
}
img.src="http://dl.dropbox.com/u/139992952/stackoverflow/fish%20overlay.png";
function draw(red,green,blue) {
ctx.save();
ctx.globalCompositeOperation = 'source-in';
ctx.fillStyle="rgb("+red+","+green+","+blue+")";
ctx.beginPath();
ctx.rect(0,0,overlay.width,overlay.height);
ctx.fill();
ctx.restore();
}
$("#red").click(function(){ draw(255,0,0); });
$("#green").click(function(){ draw(0,255,0); });
$("#blue").click(function(){ draw(0,0,255); });
});
</script>
</head>
<body>
<button id="red">Red Fish</button>
<button id="green">Green Fish</button>
<button id="blue">Blue Fish</button>
<div id="wrapper">
<img id="base" src="http://dl.dropbox.com/u/139992952/stackoverflow/fish.png" width=350 height=250>
<canvas id="overlay" width=350 height=250></canvas>
</div>
</body>
</html>
I have got my video & its playing fine, but now i need to add a logo on my video tag at right bottom corner(the coordinates(2,2,60,60) icon size is 60*60),
I thought of using canvas, but came up some thing like this..
<html>
<head>
<title>testpage</title>
<script type="text/javascript">
window.addEventListener('load', function () {
var element = document.getElementById('myCanvas');
if (!element || !element.getContext) {
return;
}
var context = element.getContext('2d');
if (!context || !context.drawImage) {
return;
}
var google_img = new Image();
google_img.addEventListener('load', function () {
context.drawImage(this, 2, 2, 60, 60);
},false);
google_img.src = "logo.png";
},false);
</script>
</head>
<body>
<div align="center" style="padding-top:25px;">
<video src="Simplevideo.mp4" width="610" height="380" type="video/mp4" controls="controls"><p>Your browser does not support the video.</p></video>
<canvas id="myCanvas" width="62" height="62">Your browser does not support HTML5 Canvas element.</canvas>
</div>
</body>
</html>
any help to get it..
thanks in advance
shameer ali shaik
You could simply use a div as loxxy said in a comment, but if you really want to use canvas for some reason here is a jsfiddle with your code (fixed) :
http://jsfiddle.net/aS9VG/
The trick is to set the element to an absolute position so it can overlap another element :
style="position:absolute;right:150px;bottom:300px"
I am working through the HTML5 canvas tutorial on the following website:
Mozilla Developers.
In this tutorial, they say that you can use a canvas element as the backdrop of another canvas element. I have tried to do exactly that with the following html page. Unfortunately, the debugger in chrome says failed to load resource. Am I referencing the source canvas object the correct way in the function draw2()?:
<html>
<head>
<title>CANVAS TESTING</title>
<script type="text/javascript">
function draw()
{
var ctx = document.getElementById('tutorial').getContext('2d');
ctx.translate(0,document.getElementById('tutorial').height);
ctx.scale(1,-1)
// Create gradients
var lingrad = ctx.createLinearGradient(0,0,0,150);
lingrad.addColorStop(0, '#fff');
lingrad.addColorStop(0.5, '#66CC00');
lingrad.addColorStop(0.5, '#fff');
lingrad.addColorStop(1, '#00ABEB');
var lingrad2 = ctx.createLinearGradient(0,50,0,95);
lingrad2.addColorStop(0.25, 'rgba(0,0,0,0)');
lingrad2.addColorStop(0.75, '#000');
// assign gradients to fill and stroke styles
ctx.fillStyle = lingrad;
ctx.strokeStyle = lingrad2;
// draw shapes
ctx.fillRect(10,10,130,130);
ctx.strokeRect(50,50,50,50);
}
function draw2()
{
ctx=document.getElementById('canvas').getContext('2d');
img = new Image();
img.onload = function()
{
ctx.drawImage(img,0,0);
}
img.src = document.getElementById('tutorial');
}
</script>
</head>
<body onload="draw()">
<p>This is a test of canvas element.</p>
<canvas id="tutorial" width="400" height="400" style="background-color: black"></canvas>
<br /><br />
<canvas id="canvas" width="400" height="400" style="background-color: black"></canvas>
<p>
<input type="button" onclick="draw2()" value="Draw!" />
</p>
</body>
Your solution is kinda correct but you're making it waaaay more complicated than it has to be.
All you have to do is this, nothing any fancier:
var tut = document.getElementById('tutorial');
ctx.drawImage(tut,0,0); // just put in the canvas you want to draw!
Here's a live jsfiddle example if you need more detail
Ok, I just found the answer to my question.
going off the function in Draw2(), I needed to set my img.src to the following:
img.src = document.getElementById('tutorial').toDataURL();
What this does is returns the base64 encoded data string of the png image of the canvas element.