So, I'm using this function getImageData on the "context" variable that I've made inside of the <script> part, and when I do something such as draw a rectangle then do ctx.getImageData.data[0] it will show the red value of that rectangle that I drew on the canvas. But, when I import an image and draw it onto the canvas, and try to use the getImageData.data[0] all I get is 0, which makes no sense, I'm not sure why it is not reading the image correctly. I've tried tutorials on this but they're all vague and only have segments written together.
So, when I draw the rectangle, its color value comes out just fine, but again, when I draw the image, even without drawing the rectangle on the canvas, I never get the value of that particular pixel on the image.
Can someone help me? Here's my currrent code:
<html>
<head>
<title>
Color Test :)
</title>
</head>
<body>
<canvas id = "ColorTest" width = "500" height = "500">
please don't use shitty browsers :)
</canvas>
<script>
//netscape.security.PrivilegeManage…
var canvas = document.getElementById("ColorTest")
, ctx = canvas.getContext("2d")
, image = new Image()
image.onload = function(){
ctx.drawImage(image,0,0)
}
image.src = 'Pikachu.gif'
ctx.fillStyle = "rgb(123,40,170)"
ctx.fillRect(0,0,100,100)
var imagedata = ctx.getImageData(0,0,100,100)
, spot = 0
while(imagedata.data[spot] == 0){
spot++
}
console.log(imagedata.data[0])
</script>
</body>
</html>
Does the following alert anything sensible?
image.onload = function() {
ctx.drawImage(image, 0, 0);
var id = ctx.getImageData(0,0,canvas.width,canvas.height);
alert([id.data[0], id.data[1], id.data[2], id.data[3]].join(", "));
}
It could be that the image is transparent. Try with a single color non-transperent image.
What browser are you using? Using getImageData when loading an image from another domain is not allowed (security issue), and if I remember correctly there is some browsers that have problems determining the domain when running scripts localy
Related
I'm new to this - I just can't figure out why this isn't working. When I remove Display:none from HTML, the image works correctly so I know the path to the image is correct. But it's not drawing on the canvas. Thanks for your time.
HTML:
<canvas width="840" height="900" id="Canvas6">
Your browser does not support this feature.
</canvas>
<img src="image/logo.png" id="img1" width="825" height="272" style="display:none;">
<script type="text/javascript" src="js/main.js"></script>
Main.JS JAVASCRIPT:
var theCanvas = document.getElementById('Canvas6');
if (theCanvas && theCanvas.getContext) {
var ctx = theCanvas.getContext("2d");
if (ctx) {
//Create a variable to hold our image
var srcImg = document.getElementById("img1");
//Draw an image directly onto the canvas
ctx.drawImage(srcImg, 0,0);
//Draw a scaled down image
//drawImage(srcImg, dx, dy, dw, dh)
}
}
In html file, the first best thing you have done is used the 'script' tag right at the end of the html file.
This ensures that the "Critical Render Time" is minimized, and the display items in HTML are shown first. (Not a huge impact on this case, because here you are using the JS to draw/display, but this approach is really good when you use your js for other purposes like calculations etc., and you don't want to stop the other HTML items from displaying because of an ongoing calculation.)
Now that the canvas is ready, its time to throw the image on the canvas.
Try using the border property (style="border: 2px dotted black") to see the container area of the canvas.
Hmmm !! But the image doesn't show in canvas. WHY ??
Images(or any other files) take atleast some time to get processed. By the time they are getting processed to be loaded on the screen, your canvas is already getting displayed. Hence you see an empty canvas.
So, the solution is to make everything else wait, till the time image gets loaded.
How do we do that ? Just use the "Event Listener".
EventListener is the property of Window object. (window.addEventListener("load", some_func_to_run , false);). We generally use this, when we want our window/page/browser to wait for something, but hey , we can use it for our images as well.
var cvs = document.getElementById("canvas"); // Getting the control of the canvas
var ctx = cvs.getContext("2d"); //Getting the control of the useful HTML object getContext . This object brings in a lot of useful methods like drawImage, fillRect etc.
//create images
var bg = new Image(); // Creating image objects
bg.src = "images/bg.png"; //Setting the source file
//create images ends
//load images first
bg.addEventListener("load" , draw , false); //**IMPORTANT : Just remove this line and you will start facing this problem of empty canvas again
//loading images ends
function draw() {
ctx.drawImage(bg,0,0); // Putting the image and its coordinates on the canvas
}
draw(); // Calling the draw function to put the image on canvas
<html>
<body>
<canvas id="canvas" width="288" height="512" style="border: 2px dotted black"> </canvas>
<script src="flappyBird.js"></script>
</body>
</html>
So, it all about using Event Listener and asking everything to wait till the image gets loaded.
Hope this help. :)
If you try to place an image on a Canvas before it has loaded, it will not show. It is not like the img tag that will show the image whenever it loads. I surrounded your JS with an onload and it worked for me.
document.getElementById("img1").onload = function() { /* Your JS */ };
You have to wait for the image to load before you can draw it on the canvas, so set your drawing code to run on the window load event (by which time all images are loaded). Also, you don't need to include the markup for the image on the page, where you have to then prevent it from displaying with CSS. You can just create the image object and set the source attribute in the javascript. For example:
var img = document.createElement('img');
img.src = 'image/logo.png';
window.addEventListener('load', function(){
var theCanvas = document.getElementById('Canvas6');
if (theCanvas && theCanvas.getContext) {
var ctx = theCanvas.getContext("2d");
if (ctx) {
ctx.drawImage(img, 0,0);
}
}
});
In html5, when you draw to a canvas using putImageData(), if some of the pixels you are drawing are transparent (or semi-transparent), how do you keep old pixels in the canvas unaffected?
example:
var imgData = context.createImageData(30,30);
for(var i=0; i<imgData.data.length; i+=4)
{
imgData.data[i]=255;
imgData.data[i+1]=0;
imgData.data[i+2]=0;
imgData.data[i+3]=255;
if((i/4)%30 > 15)imgData.data[i+3] = 0;
}
context.putImageData(imgData,0,0);
The right half of the 30x30 rect is transparent.
If this is drawn over something on the canvas, pixels behind the right half are removed (or become thransparent). How do I keep them?
You can use getImageData to create a semi-transparent overlay:
create a temporary offscreen canvas
getImageData to get the pixel data from the offscreen canvas
modify the pixels as you desire
putImageData the pixels back on the offscreen canvas
use drawImage to draw the offscreen canvas to the onscreen canvas
Here's example code and a Demo: http://jsfiddle.net/m1erickson/CM7uY/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
// draw an image on the canvas
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stack1/landscape1.jpg";
function start(){
canvas.width=img.width;
canvas.height=img.height;
context.drawImage(img,0,0);
// overlay a red gradient
drawSemiTransparentOverlay(canvas.width/2,canvas.height)
}
function drawSemiTransparentOverlay(w,h){
// create a temporary canvas to hold the gradient overlay
var canvas2=document.createElement("canvas");
canvas2.width=w;
canvas2.height=h
var ctx2=canvas2.getContext("2d");
// make gradient using ImageData
var imgData = ctx2.getImageData(0,0,w,h);
var data=imgData.data;
for(var y=0; y<h; y++) {
for(var x=0; x<w; x++) {
var n=((w*y)+x)*4;
data[n]=255;
data[n+1]=0;
data[n+2]=0;
data[n+3]=255;
if(x>w/2){
data[n+3]=255*(1-((x-w/2)/(w/2)));
}
}
}
// put the modified pixels on the temporary canvas
ctx2.putImageData(imgData,0,0);
// draw the temporary gradient canvas on the visible canvas
context.drawImage(canvas2,0,0);
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=200 height=200></canvas>
</body>
</html>
Alternatively, you might check out using a linear gradient to do your effect more directly.
http://jsfiddle.net/m1erickson/j6wLR/
Problem
As you know, your statement
if((i/4)%30 > 15)imgData.data[i+3] = 0;
will make pixels on the right half of the image be transparent, so that any other object on the page behind the canvas can be seen through the canvas at that pixel position. However, you are still overwriting the pixel of the canvas itself with context.putImageData, which replaces all of its previous pixels. The transparency that you add will not cause the previous pixels of to show through, because the result of putImageData is not a second set of pixels on top of the previous pixels in the canvas, but rather the replacement of existing pixels.
Solution
I suggest that you begin your code not with createImageData which will begin with a blank set of data, but rather with getImageData which will give you a copy of the existing data to work with. You can then use your conditional statement to avoid overwriting the portion of the image that you wish to preserve. This will also make your function more efficient.
var imgData = context.getImageData(30,30);
for(var i=0; i<imgData.data.length; i+=4)
{
if((i/4)%30 > 15) continue;
imgData.data[i]=255;
imgData.data[i+1]=0;
imgData.data[i+2]=0;
imgData.data[i+3]=255;
}
context.putImageData(imgData,0,0);
Something that tripped me up that may be of use... I had problems with this because I assumed that putImageData() and drawImage() would work in the same way but it seems they don't. putImageData() will overwrite existing pixels with its own transparent data while drawImage() will leave them untouched.
When looking into this I just glanced at the docs for CanvasRenderingContext2D.globalCompositeOperation (should have read more closely), saw that source-over is the default and didn't realise this would not apply to putImageData()
Drawing into a temporary canvas then and using drawImage() to add the temp canvas to the main context was the solution I needed so cheers for that.
I wanted to copy a CRISP, un modified version of the canvas on top of itself. I eventually came up with this solution, which applies.
https://jsfiddle.net/4Le454ak/1/
The copy portion is in this code:
var imageData = canvas.toDataURL(0, 0, w, h);
var tmp = document.createElement('img');
tmp.style.display = 'none'
tmp.src = imageData;
document.body.appendChild(tmp);
ctx.drawImage(tmp, 30, 30);
What's happening:
copy image data from canvas
set image data to a non-displayed <img> (<img> has to be in dom though)
draw that image back onto the canvas
you can delete or reuse the <img> at this point
It is an old question, but I had a similar issue and came up with another solution that fits me better (similar to #popClingwrap's answer, but I'll elaborate a bit more). I have a WebWorker and I want it to copy and paste an svg file multiple times in an existing canvas. If the source of your ImageData is another Canvas, and you want to copy the data to another canvas, there is an easier way than manipulating pixel values in a loop. the ctx.drawImage() function does overlay images respecting transparency and can also take another canvas as source.
So I used Canvg to create a source canvas containing my source image ( For your application this will look different)
const cnv = new OffscreenCanvas(100, 100);
const loadCanvas = async () => {
const v = await Canvg.from(cnv.getContext("2d"), src, preset);
await v.render();
};
For your example this would probably look something like this
var cnv = document.createElement('canvas');
var ctx = cnv.getContext('2d');
cnv.width = 30;
cnv.height = 30;
ctx.putImageData(imgData, 0, 0);
And then you can draw this transparent image on top of an existing image as often as needed with:
ctx.drawImage(cnv, 0, 0);
11I'm using sketch.js from here: http://intridea.github.io/sketch.js/ and jquery 2.0.0
On my page, I have a list of images presented like so:
<img src="http://url.to/image"><br><span class="background">click for background</span>
and a canvas, set up like so:
<canvas id="simple_sketch" style="border: 2px solid black;"></canvas>
relevant JavaScript:
var winwidth = 800;
var winheight = 600;
$('#simple_sketch').attr('width', winwidth).attr('height', winheight);
$('#simple_sketch').sketch();
$('.background').on('click', function(event) {
event.preventDefault();
var imgurl = $(this).parent().attr('href');
console.log('imgurl: ' + imgurl);
var n = imgurl.split('/');
var size = n.length;
var file = '../webkort/' + n[size - 1];
var sigCanvas = document.getElementById('simple_sketch');
var context = sigCanvas.getContext('2d');
var imageObj = new Image();
imageObj.src = imgurl;
imageObj.onload = function() {
context.drawImage(this, 0, 0,sigCanvas.width,sigCanvas.height);
};
alert('background changed');
});
Backgrounds are changed just as I want them to, but whenever I click on the canvas, the backgound image is cleared. As per a suggestion on this thread: html5 canvas background image disappear on mousemove I commented out this.el.width = this.canvas.width(); on line 116 of sketch.js, but to no avail.
Any help appreciated!
EDIT: jsfiddle: http://jsfiddle.net/RXFX4/1/
EDIT: Couldn't figure out how to do this with sketch.js, so instead went with jqScribble (link posted in comments) which has the ability to do this as a built-in function instead.
Find this line on the library - sketch.js and delete/comment it out.
this.el.width = this.canvas.width();
Good luck
Assign the url on the image source after the onload event. If the image is already loaded, the event is probably firing before you are hooking it. Which means that your drawImage is never being called.
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(this, 0, 0,sigCanvas.width,sigCanvas.height);
};
imageObj.src = imgurl;
EDIT: I'm going to take a shot in the dark here, since I'm not familiar with sketchjs
I'm thinking that your problem is that you are completely re-render the canvas when you click your 'change background' link. Notice that if you draw, then click the change background, you lose your drawing.
However, notice that once you click again, the background disappears, and you get your original drawing back again. This tells me that sketchjs is keeping track of what has been drawn on it's own in-memory canvas, and then it drops it onto the target. The problem, then, is that when this in-memory canvas is drawn, it completely replaces the contents of the target canvas with it's own.
I notice in some of the sketchjs examples, if you want a background they actually assign the canvas a background style. In your example, you are drawing the background directly onto the canvas. The prior probably works because sketchjs knows to incorporate the background style when it draws. However, it does not know that when you drew your fresh background image, it should be using that.
Can you just change the background style on the canvas element, instead of drawing directly on the canvas?
Would it be possible to fill a png with transparency with a pattern (a repeatable texture)?
Here's a quick example of loading an image onto the canvas, just not sure how to fill it with a pattern, if that isn't possible then would there be a way to extract a path from the png?
<script>
var c = document.getElementById("a");
var ctx = c.getContext("2d");
var test= new Image();
test.src = "images/test.png";
test.onload = function() {
ctx.drawImage(test, 0, 0);
};
</script>
<body>
<canvas id="a"></canvas>
</body>
I've also created a jsfiddle with an actual loaded png
This is the effect I'm looking to achieve
Update
working example based on Simon Sarris' answer
http://jsfiddle.net/sergeh/G8egW/6/
First, draw the image to Canvas.
Then do globalCompositeOperation = 'source-in';
Then draw the pattern. It will only exist where the image was.
http://jsfiddle.net/G8egW/2/
If you had stuff already on the canvas before this time, you'll need to do the above operations on an in-memory canvas and then draw that canvas to your normal canvas. Like this:
http://jsfiddle.net/G8egW/5/
(notice the difference in the grid)
I have a html page like this:
<html>
<body>
(1)<canvas id="cs"></canvas>
(2)<img src="/image.png" id="img"/>
</body>
</html>
I would like to know how I could load and display the image (2) in the canvas (1) (with drawImage function).
I tried this but it doesn't work :
var img = $("#img");
ctx.drawImage(img,0,0);
You have to ensure that your image has loaded first. Try wrapping your drawImage call in a ready statment and make certain you are setting up your canvas object first.
$().ready(function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(document.getElementById("img"),0,0);
})
If you haven't already found it here is a nice tutorial: https://developer.mozilla.org/en/Canvas_tutorial/Using_images
Is that all of your code?
You need to set up the canvas first:
var ctx = document.getElementById('cs').getContext('2d');
var img = new Image();
img.src=document.getElementById('img').src;
ctx.drawImage(img,0,0);
Something like that...
Here's an example in jsfiddle: http://jsfiddle.net/vTYqS/
Note that the first picture gets cut off because of the default canvas size. Depending on the image you plan to copy, you may need to resize your canvas like this:
http://jsfiddle.net/vTYqS/1/