transparent image background html5 canvas - javascript

I'm inserting an image into my canvas with this:
ctx.drawImage(myImageObject, 0, 0);
it works perfectly, except the image I insert has some parts of it as transparent and canvas seems to ignore this and it just prints what should be transparent as white pixels.
Here is the image I am inserting: http://i44.tinypic.com/25ymq.gif
I researched this problem abit and some people fixed it by doing ctx.getImageData(0, 0, width, height).data and then iterating through that array replacing pixels manually for transparency. I also read that this is bad practise because its slow (and my sprite sheets could be 1000 x 1000 and so this WOULD be very slow).
Is it possible to do something to make the transparency in my gif show up? When I saved it in photoshop and when I look at the gif itself I can see the transparency, but as soon as I stick it in a canvas it stops being transparent.
edit: I just tried another gif and the transparency works, but in the one above it does not, could there possibly be a problem with the above gif?

Works fine for me with that image and the following code in the latest Firefox and Chrome beta on Mac. (Except the image itself has a few white non-transparent pixels, which you can see by opening on a dark background e.g. in Firefox.)
<!DOCTYPE HTML>
<html>
<head>
<script type="application/x-javascript">
var canvas, ctx;
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var size=500;
ctx.fillStyle = 'yellow';
ctx.beginPath();
ctx.fillStyle = 'yellow';
ctx.moveTo(0,0);
ctx.lineTo(size,0);
ctx.lineTo(size,size);
ctx.lineTo(0,size);
ctx.lineTo(0,0);
ctx.stroke();
ctx.fill();
var img = document.getElementById("img");
ctx.drawImage(img, 0, 0);
}
</script>
</head>
<body onload="init();">
<canvas id="canvas" width="500" height="500"></canvas>
<img id="img" src="test.gif" style="position:absolute; top:500px"></img>
</body>
</html>

Related

How to put a image and text on background image using Canvas or jQuery?

I'm trying to put a image and text on background image using Canvas/jQuery, but i don't no how to do this. I need to do like this image http://static.catfly.com/quiz/which-friend-should-be-kidnapted-by-aliens/en/cover.jpg
I already tried and found some script for a blog but it's not complete script, it's only made a circle, anyone can help me please?
Here is my script below.
<body onload="displayImage()">
<script type="text/javascript">
//Global variables
var myImage = new Image(); // Create a new blank image.
// Load the image and display it.
function displayImage()
{
// Get the canvas element.
canvas = document.getElementById("myCanvas");
// Make sure you got it.
if (canvas.getContext)
{
// Specify 2d canvas type.
ctx = canvas.getContext("2d");
// When the image is loaded, draw it.
myImage.onload = function() {
// Load the image into the context.
ctx.drawImage(myImage, 0, 0);
// Get and modify the image data.
changeImage();
}
// Define the source of the image.
myImage.src = "https://pbs.twimg.com/profile_image/843519123711803393/pyYe9LFq_400x400.jpg";
}
}
function changeImage()
{
ctx.strokeStyle = "white";
ctx.lineWidth = "100";
ctx.beginPath();
ctx.arc(100, 100, 150, 0, Math.PI * 2, true);
ctx.closePath();
ctx.stroke();
}
</script>
<canvas id="myCanvas" width="200" height="200"></canvas>
</body>
One of the problems is that the canvas is only 200x200 and the line width of the circle is 100, and white, so when drawn it fills most of the canvas (it's also drawn slightly outside the canvas area in this case).
And, the image in question also has a load error which may be the primary cause here (onerror+onabort handlers should always be added).
Simply adjust down the line width, fix the image, and I would also recommend setting the canvas bigger (it can be set using the image size).

Pixels left after clearing a circle in HTML5 canvas due to antialiasing

I tried to draw and then clear a circle in HTML5 Canvas.
Below is the complete code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas Circle Draw & Clear</title>
</head>
<body>
<canvas id="canvas" width="100" height="100"></canvas>
<script>
var ctx = document.getElementById('canvas').getContext('2d');
ctx.beginPath();
ctx.arc(50,50, 50, 0, 2 * Math.PI);
ctx.clip();
ctx.fillStyle = 'green';
ctx.fill();
ctx.beginPath();
ctx.arc(50, 50, 50, 0, 2 * Math.PI);
ctx.clip();
ctx.clearRect(0, 0 , 100, 100);
</script>
</body>
</html>
When I open the page with Firefox and Safari, there's a faint green circle left. When using Chrome and Opera, the circle is completely cleared. There's a JSFiddle with the same code as above. So far I've tested on both Windows and OSX with the same result.
I understand that is the result of anti-aliasing, but I wonder why the generated pixels are not erased? How can I completely remove the circle in Firefox/Safari?
Edit: I don't want to clear the whole canvas. Just want to remove the circle completely without affecting all other pixels (Thanks to #relfor reminding me that).

HTML canvas coordinates are different when created using JS versus embed in HTML

Playing with HTML5 canvas and JS, I found a strange behaviour when a canvas is added to the HTML body directly versus creating a canvas using JS.
<!DOCTYPE html>
<html>
<head></head>
<body>
<canvas id="test" width="200" height="200" style="border:1px solid #000000;">
</canvas>
<script>
var c=document.getElementById("test");
ctx=c.getContext("2d");
ctx.fillStyle = "#9ea7b8";
ctx.fill();
ctx.moveTo(0,0);
ctx.lineTo(200,200);
ctx.stroke();
// creating canvas using JS
c = document.createElement("canvas");
c.id="MyCanvas";
c.style.width="200px";
c.style.height="200px";
c.style.border="1px solid #000000";
ctx=c.getContext("2d");
ctx.fillStyle = "#9ea7b8";
ctx.fill();
ctx.moveTo(0,0);
ctx.lineTo(200,200);
ctx.stroke();
document.body.appendChild(c);
</script>
</body>
</html>
Please see the code & ouput here
I expected the line (stroke) to be a consistent diagonal across the canvas but alas!. Please help me know where am I going wrong!
Note: I forgot to mention, I tried this on Chrome only not sure if the behaviour is consistent for other browsers.
So, basically if you change from style to attribute it works.
Why ?
It seems that the width and height attributes determine the width or height of the canvas's coordinate system, whereas the CSS properties just determine the size of the box in which it will be shown.
Source
Like this it will work fine:
var c = document.getElementById("test");
ctx = c.getContext("2d");
ctx.fillStyle = "#9ea7b8";
ctx.fill();
ctx.moveTo(0, 0);
ctx.lineTo(200, 200);
ctx.stroke();
// creating canvas using JS
c = document.createElement("canvas");
c.id = "MyCanvas";
c.setAttribute("width", "200px")
c.setAttribute("height", "200px")
c.style.border = "1px solid #000000";
ctx = c.getContext("2d");
ctx.fillStyle = "#9ea7b8";
ctx.fill();
ctx.moveTo(0, 0);
ctx.lineTo(200, 200);
ctx.stroke();
document.body.appendChild(c);
<canvas id="test" width="200" height="200" style="border:1px solid #000000;"></canvas>
Canvas width and height attributes are not the same as its CSS width and height. Setting canvas.width/height attributes determines the total drawable pixel area, which can be (but does not need to be) scaled with CSS to be larger or smaller on the screen.
Normal scenario: Make canvas attribute bounds larger than CSS bounds
In fact, to make a high density display canvas it is necessary to set canvas.width and canvas.height twice as large as the css. In other words you might do:
// Two canvas pixels per screen pixel so it looks nice
// on a high density (in this case pixel ratio: 2) display
canvas.width = 800;
canvas.height = 800;
canvas.style.width = '400px';
canvas.style.height = '400px';
Normal scenario: Make canvas attribute bounds smaller than CSS bounds
On the flip side in order to make some apps like games fast canvas.width and canvas.height might be restricted to 640x480 (or something small) and then scaled with CSS to take up the whole screen. Since the total number of pixels handled on the canvas is small, the game will be faster than if you used a really large canvas and filled the screen. Obviously the game will look different, since CSS will be scaling the graphics (for better or worse).

Grid with clicable irregular shapes

I'm having a bit of trouble here to develop this functionality since it must work on IE9+ so css clip-path is not an option ( http://caniuse.com/#feat=css-clip-path ).
The issue:
I need to create a grid composed of 6 elements.
Each element is an image.
The images can be different according to user answers before getting to the grid page.
Eeach element / image must be clicable and will acquire a "selected" class that will overlay div with text and background image.
image:
What is the best way to achieve this?
One way to do this could be to save out each combination of the six images you require into one big image. Then, depending on the user's answer combination, you insert the corresponding image as a background-image of a div. You then overlay click-able hotspots within the same div that roughly correlate to the dividing edges.
This may however not be the most practical solution and largely depends on how many answers/images you are dealing with.
Alternatively you could draw SVG shapes and set their fills to the images you require.
I can recommend Raphael.js as a starting point. You should be able to find what you need in the documentation
Another option would be to use HTML5 canvas:
http://jsfiddle.net/julienbidoret/GKP7X/1/
(credit goes to julienbidoret for the jsfiddle)
Javascript:
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function () {
ctx.save();
ctx.beginPath();
ctx.moveTo(20, 0);
ctx.lineTo(240, 0);
ctx.lineTo(220, 240);
ctx.lineTo(0, 240);
ctx.closePath();
ctx.clip();
ctx.drawImage(img, 0, 0);
ctx.restore();
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/2/2b/Clouds.JPG";
HTML:
<canvas id="c" width="300" height="300" ></canvas>
Both SVG and canvas are supported in IE9.

Why aren't canvas lines visible?

I am building up to a rotating hypercube on an HTML5 Canvas, but before that goal I am reaching a basic difficulty with the Canvas. I have a white/uncolored canvas, and I am trying to draw lines after setting fillStyle and strokeStyle to '#000000', and I have not yet succeeded at getting any pixel on the canvas to appear other than white.
The canvas is at http://blajeny.com/tesseract.html , and the JavaScript which is part math and part old-fashioned JavaScript, is at http://blajeny.com/js/tesseract.js . The log says that it is drawing lines on the canvas, some of which should intersect the 500x500 canvas and some of which should lie completely inside the canvas, but all I can see is pure white.
The math side of it needs work in terms of projection from a higher- to a lower-dimensional surface. However the difficulty I am trying to address now is a basic HTML5 canvas issue in that I am setting a color, moving to and drawing a line to coordinates some of which overlap and some of which are within the 500x500 canvas, and not seeing anything turn black. (The JavaScript console logs the lines I am trying to draw.)
How can I get the lines I am trying to draw to show up?
You need to let canvas know when you start and stop drawing using context.beginPath() and context.stroke()/context.fill(). Here's code and a Fiddle: http://jsfiddle.net/m1erickson/Jw8XU/
<!DOCTYPE HTML>
<html>
<head>
<style>
canvas{border:1px solid red;}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(50, 75);
ctx.lineTo(150, 150);
ctx.stroke();
</script>
</body>
</html>

Categories

Resources